Okhttp overall flow chart

Configure the central OkHttpClient

OkHttpClient is the master of okHTTP and can customize various request configurations through its internal parameters

  • Dispatcher

A thread-management tool, implemented internally using the ExecutorService, which queues requests while using asynchronous requests, and controls when to execute them

  • Proxy

Configure proxy, is an enumeration, DIRECT\ HTTP\ SOCKS three values can be selected

  • Protocol

A List of supported Http versions that can be configured

  • ConnectSpec

A List of supported TCP and SSL/TLS versions

  • SocketFactory

Factory implementation class for establishing TCP connections

  • SSLSocketFactory

Factory implementation class for establishing SSL connections

  • CertificateChainCleaner

When establishing SSL links, remove useless certificate chains and only keep certificates for directly accessed addresses

  • HostnameVerifier

Verify the validity of the certificate when establishing an SSL link

  • CertificationPinner

Fixed certificate, through this class, you can set the public key of the certificate, as well as the CA authority that issued the certificate and its parent public key, mainly to prevent forged CA authority attacks

  • Authenticator

The callback interface after a permission verification failure returns to this interface only when the server status code is 401. In this interface, the token refresh operation can be implemented

  • ConnectPool

Manage reuse of HTTP connections and reduce network latency

  • Dns

The tool for resolving domain names into IP addresses uses the DNS parser provided by Java by default

Connection pooling ConnectPool

The connection pool reuse is actually a Socket, or TCP connection, based on http1.1 keep-alive mechanism, a TCP connection is not closed after the end of the request, can be reused by the same request.

Multiplexing connections greatly improves performance by eliminating the need to establish a physical connection on every request

StreamAllocation

Coordinate requests (Call), data streams (Stream), and physical connections (RealConnect). Each request creates a StreamAllocation. Because of connection pool reuse, there may be multiple Streamallocations for the same physical connection (RealConnect).

RealConnect

RealConnect is the encapsulation of physical connections, including Socket links (TCP links), TLS links. It has a allocations variable, which represents the number of Streamallocations that was established for this connection. If the allocations length is 0, that connection is free, otherwise that connection is in use.

ConnectPool

Connection reuse management class, reuse is RealConnect. When it comes to reuse, there must be mechanisms for storing, retrieving, and cleaning objects.

ConnectPool stores RealConnect with a two-ended ArrayQueue, and every time a new link is created, it is put into the connection pool and then attempts to start the cleanup thread

When a connection is attempted, the entire queue is traversed, the appropriate links are found, and the Allocations counter for RealConnect is increased by one

ConnectPool cleanup allows a maximum of five free connections, and a maximum of five minutes per connection. Based on the length of the Allocations list in RealConnect, that is, whether the number of StreamAllocation established at this connection is zero, Determines whether the state is idle

Is implemented by an asynchronous task that starts after the first call to the PUT method. First, open the while(true) loop, call cleanup to attempt cleanup, and return the wait time for the next cleanup. Then, call wait (time) method to wait, and perform the next cleanup. When the queue is empty, exit the loop to end the cleanup

The clearing conditions are as follows: 1. If the idle time of a connection exceeds 5 minutes or the number of idle connections exceeds 5, clear the connection with the longest idle time 2. If neither is satisfied, wait for the difference between the limit time and the connection with the longest idle time, and continue cleaning 3. If all connections are in use, wait for 5 minutes and continue cleaning

OKHttp cache

HTTP defines the following headers to control caching

  • ExpiresExpiration time
  • Cache-Control

When a client requests the same resource again, it first verifies whether it has passed or not. If it has not expired, it directly returns the Cache result. Otherwise, it makes a new request

  • last-modified
  • last-modified-since

Last-modified-since Header is used when a client requests the same resource. If the resource has not been modified, the server returns 304 to tell the client to reuse the cache

  • ETage
  • if-none-match

When the client requests the same resource, the server uses if-none-match to send the summary of the last resource. The server checks whether the summary has changed. If not, the server returns 304 to tell the client to use the cache directly

OKhttp caching is handled by the CacheInterceptor, which, depending on the cache strategy, decides whether to go network or to fetch the response directly from the cache, which is based on the CACHE control domain defined by HTTP

Interceptor Interceptor

Each request (except for direct reuse of the cache) will eventually call to RealCall getResponseWithInterceptorChain () method, in this method, the

  • Custom interceptorRequest and Respons can be customized by developers
  • RetryAndFollowUpInterceptorRetry and redirect, create StreamAllocation, add to chain
  • BriageInterceptorBridging the application layer and the actual network layer, that is, wrapping the request of the application layer into the request available on the network, and wrapping the Response returned by the network into the Response available on the application layer
  • CacheInterceptorCache control, using cache policies to decide whether to use caching or rerequest the network
  • ConnectInterceptorUse socket to establish socket connection, if HTTPS request or TLS connection
  • Custom NetworkInterceptorDeveloper custom, mainly used for network debugging
  • CallServerInterceptorMake data calls to the server, send and receive data

Add the variables to the list of interceptors in order, and then create a RealInterceptorChain with interceptors and index(index=0) as parameters

Then call chain.process(), which takes the index interceptor from the interceptors list and creates a new RealInterceptorChain chain chain (index=index+1). An interception from the interceptor () method passes in the new chain of interceptors as an interception parameter. After completing the task, the interceptor () method calls chain.process() to obtain the Response. In this loop, each interceptor is linked

If the current interceptor returns Response, it does. If not, an interception () method does various pre-tasks for the request and then calls chain-.process (), which does two things

  • Can you givechainTo provide to subsequentinterceptoruse
  • Try it from the next oneinterceptorTo deriveresponse

After the last CallServerInterceptor returns a Response, each interceptor can do some finishing work on the Response

The advantage of okhttp

Okhttp is a very low-level network library that implements the entire process from application layer protocols to establishing TCP connections, and provides a variety of external configuration items that can handle almost the majority of network requirements. After reading okHTTP’s source code, the most striking thing about okHTTP is its great configurability and high scalability, which I think are its biggest strengths.

High scalability

HTTP can be configured through the protocol, and the natural support for HTTP2, http2 compared to http1.1 new multiplexing, data flow, packet header compression, performance has a huge improvement, so, part of the high performance of http2 comes from http2 support

ConnectSpec allows you to configure the version and encryption mode of the encryption suite for SSL/TLS connections

For scenarios with high security requirements, HostnameVerifier can customize the certificate verification mode and CertificationPinner can be used to set fixed CA public keys to prevent CA tamper attacks

If there are special domain name resolution rules, you can use the Dns to configure your own domain name resolution service

Another advantage of high scalability is okHTTP’s interceptor mechanism, which makes it easy for developers to configure their own interceptors before and after data requests, such as adding headers, printing logs, and blocking resposne

Powerful performance

1. Performance is significantly improved over HTTP1.1 due to support for HTTP2

2. Reuse connections. Each time a connection is established, it is put into the connection pool. The next time the same request is made, the connection pool is checked to see whether there are available connections.

Okio is a wrapper and optimization of native Java IO/NIO, where buffers are designed to improve the performance of writing data