[置顶] AsyncHttpClient执行流程简单总结

一.AsyncHttpClient执行原理?
关键词:AsyncHttpClient  Request AsyncHttpReponseHandler

1.首先创建AsyncHttpClient、AsyncHttpResponseHandler和RequestParams,其中RequestParams封装请求参数;

2.通过post、get系列方法发起网络请求,AsyncHttpClient会将RequestParams、url、AsyncHttpResponseHandler等封装成Request,实际上是Runnable, 异步请求会放在线程池中执行,同步请求直接执行

3.在网络请求结果返回后,Request会通过AsyncHttpResponseHandler进行回调处理,AsyncHttpReponseHandler通过内部封装的ResponseHandler(继承于Handler,与创建AsyncHttpResponseHandler的线程的Looper绑定)来让回调在发起网络请求的线程中执行。

[置顶] AsyncHttpClient执行流程简单总结_第1张图片(图来自网络)

二.AsyncHttpClient如何执行同步请求和异步请求?
1.异步请求使用AsyncHttpClient,是将Request在线程池中执行,
AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext,
      uriRequest, contentType, responseHandler, context);
threadPool.submit(request);
同步请求使用SyncHttpClient,是直接在发起网络请求(post、get等)的线程中直接执行。
newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run();
SyncHttpClient继承于AsyncHttpClient,通过复写sendRequest()函数来实现,而非使用一个bool变量直接控制,这种实现方法调用起来更加清爽。

2.异步请求能被中止吗?同步请求呢?
同步请求和异步请求都可以被中止,通过RequestHandle来终止。但如果通过AsyncHttpClient的cancel,只能中止异步的传Context的请求。 

你可能感兴趣的:(android)