CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-squareup-okhttp--okhttp

An HTTP & SPDY client for Android and Java applications with efficient connection pooling, interceptors, and modern protocol support

Pending
Overview
Eval results
Files

http-client.mddocs/

HTTP Client Configuration

Central client configuration with support for timeouts, proxies, SSL settings, authentication, connection pooling, and protocol selection.

Capabilities

OkHttpClient

Main HTTP client for configuring and creating HTTP connections. Intended to be fully configured before sharing and treated as immutable after configuration.

/**
 * Configures and creates HTTP connections. Most applications can use a single
 * OkHttpClient for all of their HTTP requests - benefiting from a shared
 * response cache, thread pool, connection re-use, etc.
 */
public class OkHttpClient implements Cloneable {
    public OkHttpClient();
    public Call newCall(Request request);
    public OkHttpClient clone();
}

Usage Examples:

// Create default client
OkHttpClient client = new OkHttpClient();

// Create and execute request
Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

Response response = client.newCall(request).execute();

Timeout Configuration

Configure connection, read, and write timeouts for HTTP requests.

/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout.
 * @param timeout timeout duration
 * @param unit time unit for timeout
 */
public void setConnectTimeout(long timeout, TimeUnit unit);

/** Default connect timeout (in milliseconds). */
public int getConnectTimeout();

/**
 * Sets the default read timeout for new connections. A value of 0 means no timeout.
 * @param timeout timeout duration  
 * @param unit time unit for timeout
 */
public void setReadTimeout(long timeout, TimeUnit unit);

/** Default read timeout (in milliseconds). */
public int getReadTimeout();

/**
 * Sets the default write timeout for new connections. A value of 0 means no timeout.
 * @param timeout timeout duration
 * @param unit time unit for timeout  
 */
public void setWriteTimeout(long timeout, TimeUnit unit);

/** Default write timeout (in milliseconds). */
public int getWriteTimeout();

Usage Examples:

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(60, TimeUnit.SECONDS);
client.setWriteTimeout(60, TimeUnit.SECONDS);

Proxy Configuration

Configure HTTP proxy settings for client connections.

/**
 * Sets the HTTP proxy that will be used by connections created by this
 * client. This takes precedence over ProxySelector.
 * @param proxy the proxy to use, or Proxy.NO_PROXY to disable proxy use
 * @return this client for method chaining
 */
public OkHttpClient setProxy(Proxy proxy);

public Proxy getProxy();

/**
 * Sets the proxy selection policy to be used if no explicit proxy is specified.
 * @param proxySelector the proxy selector to use
 * @return this client for method chaining
 */
public OkHttpClient setProxySelector(ProxySelector proxySelector);

public ProxySelector getProxySelector();

Usage Examples:

// Set explicit proxy
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
client.setProxy(proxy);

// Disable proxy
client.setProxy(Proxy.NO_PROXY);

// Use system proxy selector
client.setProxySelector(ProxySelector.getDefault());

Cookie Handling

Configure cookie handling for automatic cookie management.

/**
 * Sets the cookie handler to be used to read outgoing cookies and write
 * incoming cookies.
 * @param cookieHandler the cookie handler to use
 * @return this client for method chaining
 */
public OkHttpClient setCookieHandler(CookieHandler cookieHandler);

public CookieHandler getCookieHandler();

Usage Examples:

// Use system cookie manager
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

Cache Configuration

Configure HTTP response caching with filesystem storage.

/**
 * Sets the response cache to be used to read and write cached responses.
 * @param cache the cache to use
 * @return this client for method chaining
 */
public OkHttpClient setCache(Cache cache);

public Cache getCache();

Usage Examples:

// Create cache in app's cache directory
File cacheDir = new File(context.getCacheDir(), "http-cache");
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024); // 10 MB
client.setCache(cache);

DNS Configuration

Configure DNS resolution for hostname lookups.

/**
 * Sets the DNS service used to lookup IP addresses for hostnames.
 * @param dns the DNS service to use
 * @return this client for method chaining
 */
public OkHttpClient setDns(Dns dns);

public Dns getDns();

Socket Factory Configuration

Configure socket factories for creating network connections.

/**
 * Sets the socket factory used to create connections. OkHttp only uses
 * the parameterless createSocket() method to create unconnected sockets.
 * @param socketFactory the socket factory to use
 * @return this client for method chaining
 */
public OkHttpClient setSocketFactory(SocketFactory socketFactory);

public SocketFactory getSocketFactory();

/**
 * Sets the socket factory used to secure HTTPS connections.
 * @param sslSocketFactory the SSL socket factory to use
 * @return this client for method chaining
 */
public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory);

public SSLSocketFactory getSslSocketFactory();

SSL/TLS Configuration

Configure SSL/TLS settings for secure connections.

/**
 * Sets the verifier used to confirm that response certificates apply to
 * requested hostnames for HTTPS connections.
 * @param hostnameVerifier the hostname verifier to use
 * @return this client for method chaining
 */
public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier);

public HostnameVerifier getHostnameVerifier();

/**
 * Sets the certificate pinner that constrains which certificates are trusted.
 * @param certificatePinner the certificate pinner to use
 * @return this client for method chaining
 */
public OkHttpClient setCertificatePinner(CertificatePinner certificatePinner);

public CertificatePinner getCertificatePinner();

Authentication Configuration

Configure authentication handling for HTTP challenges.

/**
 * Sets the authenticator used to respond to challenges from the remote web
 * server or proxy server.
 * @param authenticator the authenticator to use
 * @return this client for method chaining
 */
public OkHttpClient setAuthenticator(Authenticator authenticator);

public Authenticator getAuthenticator();

Connection Pool Configuration

Configure connection pooling for efficient connection reuse.

/**
 * Sets the connection pool used to recycle HTTP and HTTPS connections.
 * @param connectionPool the connection pool to use
 * @return this client for method chaining
 */
public OkHttpClient setConnectionPool(ConnectionPool connectionPool);

public ConnectionPool getConnectionPool();

Redirect Configuration

Configure redirect following behavior for HTTP responses.

/**
 * Configure this client to follow redirects from HTTPS to HTTP and from HTTP
 * to HTTPS.
 * @param followProtocolRedirects whether to follow protocol redirects
 * @return this client for method chaining
 */
public OkHttpClient setFollowSslRedirects(boolean followProtocolRedirects);

public boolean getFollowSslRedirects();

/**
 * Configure this client to follow redirects.
 * @param followRedirects whether to follow redirects
 */
public void setFollowRedirects(boolean followRedirects);

public boolean getFollowRedirects();

Retry Configuration

Configure retry behavior for connection failures.

/**
 * Configure this client to retry or not when a connectivity problem is encountered.
 * @param retryOnConnectionFailure whether to retry on connection failure
 */
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure);

public boolean getRetryOnConnectionFailure();

Protocol Configuration

Configure supported HTTP protocols for connections.

/**
 * Configure the protocols used by this client to communicate with remote
 * servers. By default this client will prefer the most efficient transport
 * available, falling back to more ubiquitous protocols.
 * @param protocols the protocols to use, in order of preference
 * @return this client for method chaining
 */
public OkHttpClient setProtocols(List<Protocol> protocols);

public List<Protocol> getProtocols();

/**
 * Sets the connection specifications for socket connections.
 * @param connectionSpecs the connection specifications to use
 * @return this client for method chaining
 */
public OkHttpClient setConnectionSpecs(List<ConnectionSpec> connectionSpecs);

public List<ConnectionSpec> getConnectionSpecs();

Interceptor Configuration

Configure interceptors for request and response processing.

/**
 * Returns a modifiable list of interceptors that observe the full span of each call.
 * @return modifiable list of application interceptors
 */
public List<Interceptor> interceptors();

/**
 * Returns a modifiable list of interceptors that observe a single network request and response.
 * @return modifiable list of network interceptors
 */
public List<Interceptor> networkInterceptors();

Usage Examples:

// Add logging interceptor
client.interceptors().add(new HttpLoggingInterceptor());

// Add authentication interceptor
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
            .header("Authorization", "Bearer " + getAccessToken());
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});

Dispatcher Configuration

Configure the dispatcher for asynchronous request execution.

/**
 * Sets the dispatcher used to set policy and execute asynchronous requests.
 * @param dispatcher the dispatcher to use
 * @return this client for method chaining
 */
public OkHttpClient setDispatcher(Dispatcher dispatcher);

public Dispatcher getDispatcher();

Call Management

Create and manage HTTP calls.

/**
 * Prepares the request to be executed at some point in the future.
 * @param request the request to prepare
 * @return a Call ready for execution
 */
public Call newCall(Request request);

/**
 * Cancels all scheduled or in-flight calls tagged with tag. Requests
 * that are already complete cannot be canceled.
 * @param tag the tag to match for cancellation
 * @return this client for method chaining
 */
public OkHttpClient cancel(Object tag);

Client Cloning

Create copies of configured clients for further customization.

/**
 * Returns a shallow copy of this OkHttpClient.
 * @return a new OkHttpClient with the same configuration
 */
@Override 
public OkHttpClient clone();

Usage Examples:

// Create base client
OkHttpClient baseClient = new OkHttpClient();
baseClient.setConnectTimeout(30, TimeUnit.SECONDS);

// Create specialized client for API calls
OkHttpClient apiClient = baseClient.clone();
apiClient.interceptors().add(new ApiKeyInterceptor());

// Create specialized client for file uploads
OkHttpClient uploadClient = baseClient.clone();
uploadClient.setReadTimeout(300, TimeUnit.SECONDS);
uploadClient.setWriteTimeout(300, TimeUnit.SECONDS);

Install with Tessl CLI

npx tessl i tessl/maven-com-squareup-okhttp--okhttp

docs

async-execution.md

authentication-security.md

caching.md

connection-management.md

form-data-multipart.md

http-client.md

http-utilities.md

index.md

interceptors.md

request-building.md

request-response-bodies.md

response-handling.md

tile.json