Okhttp run

  new Thread(new Runnable() {
            @Override
            public void run() {
                okHttpClient.newCall(new Request.Builder().build()).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                    }
                });

            }
        }).start();
Copy the code

Okhttp synchronization works like this, and needs to be called in a child thread, which we will analyze first

@Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }
Copy the code

A realCall is created here, and the Execute of realCall is performed here

@override public Response execute() throws IOException {The same network request cannot be executed more than twice. Synchronized (this) {if (executed) throw new IllegalStateException("Already executed "); synchronized (this) {if (executed) throw new IllegalStateException("Already executed "); executed = true; } transmitter.timeoutEnter(); transmitter.callStart(); Try {1: client.dispatcher().executed(this); 2: return getResponseWithInterceptorChain (); } finally {remove the request from the queue client.dispatcher().finished(this); }}Copy the code

Next look at 1 out of the dispatcher method

/** Used by {@code Call#execute} to signal it is in-flight. */ synchronized void executed(RealCall call) { runningSyncCalls.add(call); } public final class Dispatcher { private int maxRequests = 64; private int maxRequestsPerHost = 5; private @Nullable Runnable idleCallback; /** Executes calls. Created lazily. */ private @Nullable ExecutorService executorService; /** Ready Async calls in the order they'll be run. Private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); /** Running asynchronous calls. Includes canceled calls that Haven't finished yet. */ private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); Running synchronous calls. Includes canceled calls that Haven't finished yet. */ Private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); public Dispatcher(ExecutorService executorService) { this.executorService = executorService; } public Dispatcher() { } }Copy the code

The dispatcher is where every request is stored and removed. Every time an execute or enqueue is executed, the dispatcher simply adds the request to the queue. Focus is on the 2 getResponseWithInterceptorChain this method is the real operation request

Response getResponseWithInterceptorChain() throws IOException { // Build a full stack of interceptors. List<Interceptor>  interceptors = new ArrayList<>(); interceptors.addAll(client.interceptors()); , custom intercepters interceptors. Add (new RetryAndFollowUpInterceptor (client)); interceptors.add(new BridgeInterceptor(client.cookieJar())); interceptors.add(new CacheInterceptor(client.internalCache())); interceptors.add(new ConnectInterceptor(client)); if (! forWebSocket) { interceptors.addAll(client.networkInterceptors()); } interceptors.add(new CallServerInterceptor(forWebSocket)); Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0, originalRequest, this, client.connectTimeoutMillis(), client.readTimeoutMillis(), client.writeTimeoutMillis()); boolean calledNoMoreExchanges = false; try { Response response = chain.proceed(originalRequest); if (transmitter.isCanceled()) { closeQuietly(response); throw new IOException("Canceled"); } return response; } catch (IOException e) { calledNoMoreExchanges = true; throw transmitter.noMoreExchanges(e); } finally { if (! calledNoMoreExchanges) { transmitter.noMoreExchanges(null); }}}Copy the code

The first step above adds a user – defined interceptor, followed by five system – defined interceptors

RetryAndFollowUpInterceptor retry interceptor BridgeInterceptor here will encapsulate network data into HTTP format, the request to the server, and parse the returned HTTP format data CacheInterceptor cache interceptors, ConnectInterceptor An interceptor that connects to a server using the socket protocol. NetworkInterceptors CallServerInterceptor This is where the socket actually establishes a connection.Copy the code

Then create a RealInterceptorChain, index is 0, here is the OKHTTP request into one array chain, step by step to execute the array in the chain node, this encapsulation is good decoupling, the function of each module, but also convenient for users to customize the chain node, network access process.

The proceed method of the RealInterceptorChain is later called

public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange) throws IOException {... // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange, index + 1, request, call, connectTimeout, readTimeout, writeTimeout); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); try { Response response = chain.proceed(originalRequest); if (transmitter.isCanceled()) { closeQuietly(response); throw new IOException("Canceled"); }... }Copy the code

This intercepts from the zero interceptor array and calls each chain’s intercepter method recursively, then calls the proceed method to get each chain’s response and pass the return value.

Therefore, from the above analysis, we know that each request will go through this series of chains and get response.