An HTTP & SPDY client for Android and Java applications with efficient connection pooling, interceptors, and modern protocol support
npx @tessl/cli install tessl/maven-com-squareup-okhttp--okhttp@2.7.0OkHttp is a high-performance HTTP client library for Android and Java applications that provides comprehensive support for HTTP/1.1, HTTP/2, and SPDY protocols. The library offers a modern, fluent API for making HTTP requests with features including automatic request/response compression, connection pooling, transparent GZIP support, response caching, and seamless handling of common authentication schemes.
pom.xml or Gradle build.gradleMaven:
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>Gradle:
implementation 'com.squareup.okhttp:okhttp:2.7.5'import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
// Create client
OkHttpClient client = new OkHttpClient();
// Build request
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
// Execute synchronously
Response response = client.newCall(request).execute();
try {
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
}
} finally {
response.body().close();
}
// Execute asynchronously
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
try {
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
}
} finally {
response.body().close();
}
}
});OkHttp is built around several key components:
Central client configuration with support for timeouts, proxies, SSL settings, authentication, and connection pooling.
public class OkHttpClient implements Cloneable {
public OkHttpClient();
public Call newCall(Request request);
public OkHttpClient clone();
}Fluent API for building HTTP requests with URLs, methods, headers, and request bodies.
public final class Request {
public static class Builder {
public Builder();
public Builder url(String url);
public Builder url(HttpUrl url);
public Builder header(String name, String value);
public Builder addHeader(String name, String value);
public Builder get();
public Builder post(RequestBody body);
public Builder put(RequestBody body);
public Builder delete();
public Builder method(String method, RequestBody body);
public Request build();
}
}Comprehensive response handling with status codes, headers, and multiple body access methods.
public final class Response {
public int code();
public boolean isSuccessful();
public String message();
public Headers headers();
public ResponseBody body();
public Protocol protocol();
public Request request();
}Support for various content types with efficient streaming and multiple access patterns.
public abstract class RequestBody {
public static RequestBody create(MediaType contentType, String content);
public static RequestBody create(MediaType contentType, byte[] content);
public static RequestBody create(MediaType contentType, File file);
public abstract MediaType contentType();
public abstract void writeTo(BufferedSink sink) throws IOException;
}
public abstract class ResponseBody {
public abstract MediaType contentType();
public abstract long contentLength() throws IOException;
public final String string() throws IOException;
public final byte[] bytes() throws IOException;
public final InputStream byteStream() throws IOException;
}Builders for HTML form encoding and multipart form data with file upload support.
public final class FormEncodingBuilder {
public FormEncodingBuilder();
public FormEncodingBuilder add(String name, String value);
public FormEncodingBuilder addEncoded(String name, String value);
public RequestBody build();
}
public final class MultipartBuilder {
public MultipartBuilder();
public MultipartBuilder type(MediaType type);
public MultipartBuilder addFormDataPart(String name, String value);
public MultipartBuilder addFormDataPart(String name, String filename, RequestBody value);
public RequestBody build();
}URL handling, header management, media type parsing, and HTTP protocol utilities.
public final class HttpUrl {
public static HttpUrl parse(String url);
public String scheme();
public String host();
public int port();
public String encodedPath();
public String queryParameter(String name);
public static class Builder {
public Builder scheme(String scheme);
public Builder host(String host);
public Builder port(int port);
public Builder encodedPath(String encodedPath);
public Builder addQueryParameter(String name, String value);
public HttpUrl build();
}
}HTTP response caching with filesystem storage, cache control directives, and LRU eviction.
public final class Cache {
public Cache(File directory, long maxSize);
public void evictAll() throws IOException;
public long getSize() throws IOException;
public int getHitCount();
public int getNetworkCount();
}
public final class CacheControl {
public static final CacheControl FORCE_NETWORK;
public static final CacheControl FORCE_CACHE;
public boolean noCache();
public boolean noStore();
public int maxAgeSeconds();
public static CacheControl parse(Headers headers);
}Connection pooling, SSL/TLS configuration, and connection specifications for performance optimization.
public final class ConnectionPool {
public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs);
public int getIdleConnectionCount();
public int getConnectionCount();
public void evictAll();
}
public final class ConnectionSpec {
public static final ConnectionSpec MODERN_TLS;
public static final ConnectionSpec COMPATIBLE_TLS;
public static final ConnectionSpec CLEARTEXT;
public boolean isTls();
public List<CipherSuite> cipherSuites();
public List<TlsVersion> tlsVersions();
}Authentication handling, certificate pinning, TLS handshake management, and credential utilities.
public interface Authenticator {
Request authenticate(Proxy proxy, Response response) throws IOException;
Request authenticateProxy(Proxy proxy, Response response) throws IOException;
}
public final class CertificatePinner {
public static final CertificatePinner DEFAULT;
public void check(String hostname, List<Certificate> peerCertificates)
throws SSLPeerUnverifiedException;
public static String pin(Certificate certificate);
}
public final class Credentials {
public static String basic(String userName, String password);
}Request and response interception for logging, authentication, caching, and custom processing.
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
Connection connection();
}
}Callback-based asynchronous execution with dispatcher configuration and call management.
public interface Callback {
void onFailure(Request request, IOException e);
void onResponse(Response response) throws IOException;
}
public final class Dispatcher {
public Dispatcher();
public void setMaxRequests(int maxRequests);
public void setMaxRequestsPerHost(int maxRequestsPerHost);
public void cancel(Object tag);
public int getRunningCallCount();
public int getQueuedCallCount();
}public final class Headers {
public static Headers of(String... namesAndValues);
public static Headers of(Map<String, String> headers);
public String get(String name);
public Date getDate(String name);
public List<String> values(String name);
public Set<String> names();
public int size();
public String name(int index);
public String value(int index);
public Builder newBuilder();
public Map<String, List<String>> toMultimap();
public static class Builder {
public Builder add(String name, String value);
public Builder set(String name, String value);
public Builder removeAll(String name);
public Headers build();
}
}
public final class MediaType {
public static MediaType parse(String string);
public String type();
public String subtype();
public Charset charset();
public Charset charset(Charset defaultValue);
}
public enum Protocol {
HTTP_1_0("http/1.0"), HTTP_1_1("http/1.1"), SPDY_3("spdy/3.1"), HTTP_2("h2");
public static Protocol get(String protocol) throws IOException;
}
public enum TlsVersion {
TLS_1_2("TLSv1.2"), TLS_1_1("TLSv1.1"), TLS_1_0("TLSv1"), SSL_3_0("SSLv3");
}
public final class Call {
public Response execute() throws IOException;
public void enqueue(Callback responseCallback);
public void cancel();
public boolean isExecuted();
public boolean isCanceled();
}
public final class Challenge {
public String scheme();
public String realm();
public Map<String, String> authParams();
}
public final class Handshake {
public TlsVersion tlsVersion();
public CipherSuite cipherSuite();
public List<Certificate> peerCertificates();
public List<Certificate> localCertificates();
}
public enum CipherSuite {
// TLS 1.2 cipher suites
TLS_RSA_WITH_AES_128_CBC_SHA("TLS_RSA_WITH_AES_128_CBC_SHA"),
TLS_RSA_WITH_AES_256_CBC_SHA("TLS_RSA_WITH_AES_256_CBC_SHA"),
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"),
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
// Additional cipher suites available - over 150 constants supported
}