OkHttp request example (I can only write Java)
The steps to use OkHttp are as follows: 1. 2. Construct a request; 3. Associate the request with the client to generate a Call object. 4. Synchronous or asynchronous requests
Source code analysis
Construct a client
Construct a request
The Call object is generated by associating the request with the client
NewCall returns the Call object
NewCall is actually a Call to RealCall that returns a Call object
A synchronous request
Finally return getResponseWithInterceptorChain ()
An asynchronous request
The difference between synchronous and asynchronous requests:
Executed for synchronous requests and dispatcher.enqueue for asynchronous requests
2. A synchronous request directly returns the response result. An asynchronous request creates an AsyncCall instance and then retrits the return result through callback
dispatcher
The Dispatcher maintains three ArrayDeQues, one of which saves the synchronization tasks being performed. Arraydeques are asynchronous because the Dispatcher default supports a maximum of 64 concurrent requests, a single Host can execute a maximum of 5 concurrent requests, if more than, The Call will be placed in readyAsyncCall first. When there is an idle thread, the readyAsyncCall thread will be moved into RunningAsynccCalls to execute the request.
AsyncCall
AsyncCall implements the Runnable interface and ultimately gets a Response by calling its run() method
Through thread pools
In the run method callback getResponseWithInterceptorChain ()
getResponseWithInterceptorChain()
At this point, a complete HTTP request has been finished, both synchronous and asynchronous calls at last getResponseWithInterceptorChain () method, the next article to explain