The source version of okHTTP is 3.7.0

My habit of reading source code is to start with the entry, so let’s first look at the code flow using an OKHTTP request

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
  .get()
  .url("http://www.baidu.com")
  .build();
okHttpClient.newCall(request).enqueue(new Callback() {
  @Override
  public void onFailure(Call call, IOException e) {}
  @Override
  public void onResponse(Call call, Response response) throws IOException {}
});
Copy the code

As you can see, the smallest element of a request is the Call inside newCall().

  • A Call cannot be executed twice (i.e., enqueue or execute can only be called once)
  • A Call can be cancelled, but not always, if the request has been completed

And that’s why we keep going. RealCall can be seen in the source code is an inherited Call, so look at RealCall implementation

execute
enqueue
Call
execute
client.dispatcher().executed(call)
client.dispatcher().finished(this);

client.dispatcher().executed(call)

Then let’s look at the most critical getResponseWithInterceptorChain ()

So we know from the above that the last interceptor in the chain is executed first (the CallServerInterceptor interceptor at the top, which makes the actual network requests), and then the results are returned to each interceptor layer by layer.

Finally we look at asynchronous requests, we do client.dispatcher().enqueue(new AsyncCall(responseCallback));

client.dispatcher().executed(call)