OkHttp
The HTTP client behind most JVM and Android networking, including Retrofit's.
What it is
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.
OkHttp 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.
- Licence
- Apache 2.0
- Maintained by
- Square
When to use it
The question documentation cannot answer for you — because it cannot recommend something else.
Reach for it when
- Android applications, where it is effectively the standard
- You want connection pooling, transparent GZIP, caching and HTTP/2 without configuration
Look elsewhere when
- Java 11+ server code with simple needs — the built-in `java.net.http.HttpClient` may be enough
Installation
Add com.squareup.okhttp3:okhttp dependency in pom.xmlGetting started
The smallest useful thing you can do with it, and what each part means.
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());
}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());
}Advanced usage
Where the library earns its place over a simpler alternative.
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());
}
});Request request = new Request.Builder()
.url("https://api.example.com")
.addHeader("Authorization", "Bearer TOKEN")
.build();OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("X-Custom-Header", "value")
.build();
return chain.proceed(request);
})
.build();Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- IOException
- Occurs when network request fails. Check connectivity, URL, or request configuration.
- TimeoutException
- Occurs if a request exceeds the specified timeout. Adjust timeouts based on network conditions.
- IllegalArgumentException
- Occurs when request parameters (URL, headers, body) are invalid. Validate inputs before sending requests.
Best practices
- 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.
Alternatives
Comparable options, and the reason you would pick one over the other.
Background
Why it exists, and what it was reacting to.
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.
