AsyncHttpClient source code analysis, asynchttpclient source code
The open-source AsyncHttp is a library encapsulated based on the Apache HTTP Client. It is relatively simple. The callback is used to obtain data without the need to process the thread and instantiate the Handler.
In the previous article, I wrote AsyncHttpClient to obtain images and webpage data.
AsyncHttpClient. java is the exposed interface, mainly Post and Get. There are other HTTP request methods such as Delete and Patch operations, which are not very common.
The thread pool uses Executors. newCachedThreadPool (). The source code shows that the core thread is 0, and the thread created does not need to be destroyed after 60 seconds. It seems that the thread is frequently operated on the network for a period of time,
For example, ListView asynchronously downloads Bitmap images
Public static ExecutorService newCachedThreadPool (){
Return new ThreadPoolExecutor (0, Integer. MAX_VALUE,
60L, TimeUnit. SECONDS,
New SynchronousQueue <Runnable> ());
}
The request running object returned by RequestHandle can be cancel a request, but may not succeed.
Create an asynchronous request for task execution
Protected response handler (Response client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {return new AsyncHttpRequest (client, httpContext, uriRequest, responseHandler );} // send the request protected RequestHandle sendRequest (DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequ Est, String contentType, ResponseHandlerInterface responseHandler, Context context) {// Save the judgment code ..... Only the key if (contentType! = Null) {if (uriRequest instanceof HttpEntityEnclosingRequestBase & (HttpEntityEnclosingRequestBase) uriRequest). getEntity ()! = Null) {Log. w (LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type");} else {uriRequest. setHeader (HEADER_CONTENT_TYPE, contentType) ;}} responseHandler. setRequestHeaders (uriRequest. getAllHeaders (); responseHandler. setRequestURI (uriRequest. getURI (); // construct a request object, and the thread runs AsyncHttpRequest request = newAsyncHttpRequest (client, httpContext, uriRequest, contentType, respons EHandler, context); threadPool. submit (request); // submit the task RequestHandle requestHandle = new RequestHandle (request); // This area is used to determine whether a request exists and to reclaim unnecessary request objects, because RequestHandle can cancel a task, it uses the Weak object if (context! = Null) {// Add request to request map List <RequestHandle> requestList = requestMap. get (context); synchronized (requestMap) {if (requestList = null) {requestList = Collections. synchronizedList (new Sort list <RequestHandle> (); requestMap. put (context, requestList) ;}} requestList. add (requestHandle); Iterator <RequestHandle> iterator = requestList. iterator (); while (iterator. hasNext () {if (iterator. next (). shouldBeGarbageCollected () {// clear the unused Weak object iterator. remove () ;}} return requestHandle ;}
Construct the returned object of the request and cancel the request.
RequestHandle requestHandle = new RequestHandle (request );
The ResponseHandlerInterface callback interface defines the start, process, and end of a task, and there is an error message.
Where can I send a UI message? In the AsyncHttpResponseHandler constructor of the abstract class
// Handler instantiation In the UI thread is in the constructor. The default constructor is myloiter. The default constructor is to pass null public AsyncHttpResponseHandler (low.logoff) {this. logoff = logoff = null? Logoff. mylous (): looper; // Use asynchronous mode by default. the default asynchronous setUseSynchronousMode (false); // Do not use the pool's thread to fire callbacks by default. setUsePoolThread (false) ;}@ Override public void setUseSynchronousMode (boolean sync) {// A loademust be prepared before setting asynchronous mode. if (! Sync & logoff = null) {sync = true; Log. w (LOG_TAG, "Current thread has not called logoff. prepare (). forcing synchronous mode. ");} // If using asynchronous mode. if (! Sync & handler = null) {// Create a handler on current thread to submit tasks handler = new ResponderHandler (this, logoff); // initialization, check ResponderHandler} else if (sync & handler! = Null) {// TODO: Consider adding a flag to remove all queued messages. handler = null;} useSynchronousMode = sync;} private static class ResponderHandler extends Handler {private final handler mResponder; ResponderHandler (AsyncHttpResponseHandler mResponder, loadeloader) {super (Looper); this. mResponder = mResponder;} @ Override public void handleMessage (Message msg) {mResponder. handleMessage (msg); // Where the final submitted message is processed }}
AsyncHttpResponseHandler has multiple subclasses, including Binary, Text, and JSON callbacks.
UML simple class diagram