This article was translated from the official OkHttp Wiki document

The HTTP client’s job is to accept your request and produce its response. This is simple in theory but it gets tricky in practice.

Calls

The HttpClient receives your request and generates a response. This is simple in theory, but tricky in practice.

Requests

Each HTTP request contains a URL, a method (like GET or POST), and a list of headers. Requests may also contain a body: a data stream of a specific content type.

Each Http request contains a URL, a method (such as GET or POST), and a series of headers. A Request might contain a Body: a specific type of data stream.

Responses

The response answers the request with a code (like 200 for success or 404 for not found), headers, and its own optional body.

The Response will respond to your request with a return code (like 200 for successful request or 404 for not found), a series of request headers, and its own body.

Rewriting Requests

When you provide OkHttp with an HTTP request, you’re describing the request at a high-level: “fetch me this URL with these headers.” For correctness and efficiency, OkHttp rewrites your request before transmitting it.

When you make an Http request through OkHttp, you are describing a request at a high level: “Access this URL through these request headers.” To ensure accuracy and efficiency, Okhttp will re-write your request before requesting transmission.

OkHttp may add headers that are absent from the original request, including Content-Length, Transfer-Encoding, User-Agent, Host, Connection, and Content-Type. It will add an Accept-Encoding header for transparent response compression unless the header is If you’ve got cookies, OkHttp will add a Cookie header with them.

OkHttp may add missing headers to the original request, including Content-Length, Transfer-Encoding, user-Agent, Host, Connection, and Content-Type. OkHttp will add an Accept-Encoding header for the transparently compressed response, unless it already exists. If you want to retrieve cookies, OkHttp adds a Cookie request header.

Some requests will have a cached response. When this cached response isn’t fresh, OkHttp can do a conditional GET to download an updated response if it’s newer than what’s cached. This requires headers like If-Modified-Since and If-None-Match to be added.

Some requests will cache the response. When the cached response is not up to date, OkHttp will perform an additional Get request to download the updated response if it is newer than the cached response. This requires the addition of headers like if-modified-since and if-none-match.

Rewriting Responses

If transparent compression was used, OkHttp will drop the corresponding response headers Content-Encoding and Content-Length because they don’t apply to the decompressed response body.

If transparent compression is used, OkHttp will remove the corresponding response headers content-Encoding and Content-Length, because these headers are not suitable for compressing the response body.

If a conditional GET was successful, responses from the network and cache are merged as directed by the spec.

If a Get request is successful, the network and cached responses are merged directly according to the specification.

Follow-up Requests

When your requested URL has moved, The webserver will return a response code like 302 to indicate the document’s new URl.okhttp will follow the redirect to retrieve a final response.

When your requested URL is moved, the server will return a code, such as 302, pointing to the new URL of the document. OkHttp will follow the redirection to correct the final response.

If the response issues an authorization challenge, OkHttp will ask the Authenticator (if one is configured) to satisfy the challenge. If the authenticator supplies a credential, the request is retried with that credential included.

If the response issues an authorization request, OkHttp will ask the validator (if configured) to respond to the request. If the validator provides a credential, the request is rerequested with the credential.

Retrying Requests

Sometimes connections fail: either a pooled connection was stale and disconnected, or the webserver itself couldn’t be reached. OkHttp will retry the request with a different route if one is available.

Sometimes the connection fails: the pool connection fails and disconnects, or the server itself cannot be accessed. OkHttp retries the request with a different valid route.

Calls

With rewrites, redirects, follow-ups and retries, your simple request may yield many requests and responses. OkHttp uses Call to model the task of satisfying your request Through however many intermediate requests and responses are necessary. But it’s comforting to know that your code will continue to work if your URLs are redirected or if you failover to an alternate IP address.

By rewriting, redirecting, following up, and retrying, your simple request can generate many requests and responses. OkHttp uses Call to simulate the task of fulfilling your request, however many intermediate requests and responses are required. That’s not often the case! However, if your URL is redirected or failover to an alternate IP address, your code will still work, which is great!

Calls are executed in one of two ways:

Synchronous: your thread blocks until the response is readable. Asynchronous: you enqueue the request on any thread, and get called back on another thread when the response is readable.

Canceled Calls can be canceled from any thread. This will fail the call if it hasn’t yet completed! Code that is writing the request body or reading the response body will suffer an IOException when its call is canceled.











Dispatch

For synchronous calls, you bring your own thread and are responsible for managing how many simultaneous requests you make. Too many simultaneous connections wastes resources; too few harms latency.

For asynchronous calls, Dispatcher implements policy for maximum simultaneous requests. You can set maximums per-webserver (default is 5), and overall (default is 64).








Connections

Although you provide only the URL, OkHttp plans its connection to your webserver using three types: URL, Address, and Route.

Although you only provide the URL, OkHttp uses three forms to connect to the server: URL, address, and route.

URLS

URLs (like github.com/square/okht…). are fundamental to HTTP and the Internet. In addition to being a universal, decentralized naming scheme for everything on the web, they also specify how to access web resources.

Urls are the foundation of Http and the web. In addition to being used as a unified, decentralized naming scheme on the Web, they also specify how to access Web resources.

URLs are abstract:

They specify that the call may be plaintext (http) or encrypted (https), but not which cryptographic algorithms should be used. Nor do they specify how to verify the peer’s certificates (the HostnameVerifier) or which certificates can be trusted (the SSLSocketFactory). They don’t specify whether a specific proxy server should be used or how to authenticate with that proxy server.








They’re also concrete: each URL identifies a specific path (like /square/okhttp) and query (like ? q=sharks&lang=en). Each webserver hosts many URLs.


Addresses

Addresses specify a webserver (like github.com) and all of the static configuration necessary to connect to that server: the port number, HTTPS settings, and preferred network protocols (like HTTP/2 or SPDY).

URLs that share the same address may also share the same underlying TCP socket connection. Sharing a connection has substantial performance benefits: lower latency, higher throughput (due to TCP slow start) and conserved battery. OkHttp uses a ConnectionPool that automatically reuses HTTP/1.x connections and multiplexes HTTP/2 and SPDY connections.











In OkHttp some fields of the address come from the URL (scheme, hostname, port) and the rest come from the OkHttpClient.

Routes

Routes supply the dynamic information necessary to actually connect to a webserver. This is the specific IP address to attempt (as discovered by a DNS query), the exact proxy server to use (if a ProxySelector is in use), and which version of TLS to negotiate (for HTTPS connections).

There may be many routes for a single address. For example, a webserver that is hosted in multiple datacenters may yield multiple IP addresses in its DNS response.

Connections

When you request a URL with OkHttp, here’s what it does:

It uses the URL and configured OkHttpClient to create an address. This address specifies how we’ll connect to the webserver. It attempts to retrieve a connection with that address from the connection pool. If it doesn’t find a connection in the pool, it selects a route to attempt. This usually means making a DNS request to get the server’s IP addresses. It then selects a TLS version and proxy server if necessary. If it’s a new route, it connects by building either a direct socket connection, a TLS tunnel (for HTTPS over an HTTP proxy), or a direct TLS connection. It does TLS handshakes as necessary. It sends the HTTP request and reads the response. If there’s a problem with the connection, OkHttp will select another route and try again. This allows OkHttp to recover when a subset of a server’s addresses are unreachable. It’s also useful when a pooled connection is stale or if the attempted TLS version is unsupported.














Once the response has been received, the connection will be returned to the pool so it can be reused for a future request. Connections are evicted from the pool after a period of inactivity.