Okhttp interview--okhttp The entire asynchronous request process

Source: Internet
Author: User

From the previous section, we have learned how to send asynchronous requests using okhttp, download network picture information and display it on the ImageView control, and from this section we begin to look at the internal implementation process and principles. Because the whole process is relatively complex, I divide the analysis into the following chapters to introduce

    1. Process overview
    2. The principle of interceptors
    3. Process analysis of SendRequest in Httpengine
    4. Process analysis of Readresponse in Httpengine

In this section we take a look at an overview of the entire process, first a time series diagram

In slices from http://www.jianshu.com/p/db197279f053

From the use of some of the okhttp began to analyze:
In the previous section, we created a call object by using the Okhttpclient.newcall (Request) method,
Call is an interface code as follows:

package okhttp3;import java.io.IOException;publicinterface Call {  Request request();  throws IOException;  void enqueue(Callback responseCallback);  void cancel();  boolean isExecuted();  boolean isCanceled();  interface Factory {    Call newCall(Request request);  }}

So okhttpclient need to give us a call interface implementation class, click to see, the code is as follows:

/**   * Prepares the {@code request} to be executed at some point in the future.   */  @OverridepublicnewCall(Request request) {    returnnew RealCall(this, request);  }

It can be found that the Realcall object is actually returned.

Next, call the Call.enqueue (Callback) method in the activity, and then enter the code as follows:

In the Enqueue method, the method of the 2 parameter is called, and the second parameter is forwebsocket to False.

In the Enqueue method of the 2 parameter, we find that the Client.dispatcher.enqueue method is finally called, and the callback and forwebsocket two parameters are encapsulated in an object called Asynccall.

This dispatcher is a global variable in okhttpclient, click to see the following:

synchronized void Enqueue (Asynccall  call ) {if  (Runningasynccalls. Size  () < maxrequests && Runningcallsforhost (call ) < Maxrequestsperhost) {Runningasynccalls.      Add  (call );     Executorservice (). Execute (call );     } else {Readyasynccalls.add (call );  }  }

Dispatcher internal is a thread pool to execute, more than the maximum number of requests to join the queue to prepare the request, for this thread pool will be followed by a separate blog to explain, at this time we mainly to tidy up the entire request process, so do not explain too much. The above code executes to the if code block and then executes Executorservice (). Execute (call); See this for the thread pool to understand the classmate should be able to immediately think of Asynccall is actually a runnable object, we point into Asynccall code can see it is inherited namedrunnable, The namedrunnable implements the Runnable interface and invokes the Execute method actively in the Run method, as follows:

This abstract execute method has been implemented in Asynccall, as follows:

As you can see, when executing a asynccall Execute method, a method called Getresponsewithinterceptorchain is called, and the response object is returned, This response is then returned through an interface callback to the callback interface that we implemented in the activity and refreshes the UI.

How does this getresponsewithinterceptorchain internal work?? In fact, the source code in this method is very simple, as follows:

Create a Applicationinterceptorchain object and call its proceed method, and then look at Applicationinterceptorchain proceed code as follows

In the proceed method, it is determined that if index is less than the number of interceptor sets in Okhttpclient, a new Applicationinterceptorchain object is created recursively. and the Intercept method of passing the new Applicationinterceptorchain object to the interceptor of index subscript

Note: Here is a highlight, If we want to implement intercept we must actively invoke the Chain.proceed method in the Intercept method so that the entire recursive loop can be executed smoothly, and conversely we can intercept the network request in an interceptor, as long as the proceed party is not called in the Interceptor Method can

For the role and principle of interceptors, I will analyze them separately in subsequent chapters.


But in this recursive loop, the final index will be in a >=client.interceptors.size phase, so the last line of code GetResponse (request, Forwebsocket) method will eventually be called. This method is really a way to send a network request and get response, whose internal code looks like this:

, a Httpengine object is created in the GetResponse method, and then the SendRequest and Readresponse methods of Httpengine are called, respectively, to send the network request and read the results of the network request. Finally, return the response object to the previously described Getresponsewithinterceptorchain method and pass it back to the callback in the activity.

Subsequent analysis will be done separately for the Httpengine internal implementation.

Finally, we use two graphs to make a summary of the process.




Okhttp interview--okhttp The entire asynchronous request process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.