private void testOkHttp(a) {
    OkHttpClient client = new OkHttpClient();
    // 1. Asynchronous invocation
    client.newCall(new Request.Builder().build()).execute();
    // 2. Synchronous invocation
    client.newCall(new Request.Builder().build()).enqueue(new Callback() {});
}
Copy the code
Ruminate:1.This code involves TCP/IP protocol knowledge of what aspects2.Why was it done this way, and what design patterns did it useCopy the code

Simple process description:

1, synchronization, began to call directly RealCall getResponseWithInterceptorChain, construct multiple interceptors, each division of interceptors handle the Request2, asynchronously add tasks to the queue, and then multithreading from the queue to start the execution of the Request, the use of the double queue, one for the waiting queue, one for the execution queue, in the child thread for each Request to create multiple interceptors, each interceptor division of processing Request.Copy the code

After a brief description of the initialization process and a dive into the specifics of each interceptor, OKHTTP comes with the first interceptor, BridgeInterceptor, which mainly encapsulates the request header

1. BridgeInterceptor

@Override 
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    RequestBody body = userRequest.body();
    if(body ! =null) {
      	MediaType contentType = body.contentType();
      	if(contentType ! =null) {
            requestBuilder.header("Content-Type", contentType.toString());
      	}
      	long contentLength = body.contentLength();
      	if(contentLength ! = -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
      	} else {
            requestBuilder.header("Transfer-Encoding"."chunked");
            requestBuilder.removeHeader("Content-Length"); }}if (userRequest.header("Host") = =null) {
      	requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") = =null) {
      	requestBuilder.header("Connection"."Keep-Alive");
    }
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") = =null && userRequest.header("Range") = =null) {
      	transparentGzip = true;
      	requestBuilder.header("Accept-Encoding"."gzip");
    }
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if(! cookies.isEmpty()) { requestBuilder.header("Cookie", cookieHeader(cookies));
    }
    if (userRequest.header("User-Agent") = =null) {
      	requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      	GzipSource responseBody = new GzipSource(networkResponse.body().source());
      	Headers strippedHeaders = networkResponse.headers().newBuilder()
            .removeAll("Content-Encoding")
            .removeAll("Content-Length")
            .build();
      	responseBuilder.headers(strippedHeaders);
      	String contentType = networkResponse.header("Content-Type");
      	responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }
    return responseBuilder.build();
}
Copy the code

This interceptor is the simplest one in the interceptors in the responsibility chain. As for the above code, do not memorize it by rote when reviewing it in the future. Just remember that OKHTTP uses interceptors to divide the processing of requests, and clearly defines the responsibilities of each interceptor to improve scalability and reuse. Each interceptor does its job.

2. Request header

I looked up the HTTP/ TCP/IP diagram and found that most of the articles on the web were excerpts from related books

HTTP header fields are classified into the following four types based on actual usage:

1. General header field

Header used by both request and response packets

2. Request header fields

The header used for sending request packets from the client to the server, which contains additional information about the request, client information, and priority of the response content

3. Response header fields

The header used when sending a response packet from the server to the client supplements the additional content of the response and requires the client to attach additional content information.

4. Entity header field

For the headers used in the entity part of the request message and response message, information related to the entity such as the update time of the resource content is added.