OkHttp

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.

Installation

maven: Add com.squareup.okhttp3:okhttp dependency in pom.xml
gradle: Add implementation 'com.squareup.okhttp3:okhttp:4.11.0' in build.gradle

Usage

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.

Simple GET request

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.

Simple POST request with JSON

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.

Asynchronous request

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.

Adding headers

Request request = new Request.Builder()
    .url("https://api.example.com")
    .addHeader("Authorization", "Bearer TOKEN")
    .build();

Demonstrates adding custom HTTP headers to a request.

Connection pooling and timeouts

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build();

Configures OkHttp client with custom timeouts for connection and reading.

Using interceptors

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.

Error Handling

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.