Language: Java
Web
OkHttp was created by Square to provide a reliable and performant HTTP client for Java applications. It handles connection management, retries, caching, and asynchronous requests efficiently, making it popular for REST API clients.
OkHttp is a modern, efficient, and feature-rich HTTP client for Java and Android. It supports HTTP/1.1, HTTP/2, WebSocket, connection pooling, and transparent GZIP compression.
Add com.squareup.okhttp3:okhttp dependency in pom.xmlAdd implementation 'com.squareup.okhttp3:okhttp:4.11.0' in build.gradleOkHttp allows developers to send synchronous and asynchronous HTTP requests, manage headers and cookies, handle redirects, and stream responses. It integrates seamlessly with JSON libraries like Gson or Jackson.
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}Sends a synchronous GET request to a URL and prints the response body.
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String json = "{\"name\":\"Alice\"}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://httpbin.org/post")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}Sends a POST request with a JSON payload.
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});Executes an HTTP request asynchronously using a callback.
Request request = new Request.Builder()
.url("https://api.example.com")
.addHeader("Authorization", "Bearer TOKEN")
.build();Demonstrates adding custom HTTP headers to a request.
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();Configures OkHttp client with custom timeouts for connection and reading.
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("X-Custom-Header", "value")
.build();
return chain.proceed(request);
})
.build();Uses an interceptor to modify requests globally.
Reuse `OkHttpClient` instances to leverage connection pooling.
Use asynchronous calls for network operations to avoid blocking the main thread.
Use interceptors for logging, authentication, or request/response modification.
Handle network exceptions gracefully and implement retries if necessary.
Integrate with JSON libraries like Gson or Jackson for payload serialization/deserialization.