AsyncHttpClient源码解析

 

AsyncHttpClient 有几个构造方法。

最终调用都是public AsyncHttpClient(SchemeRegistry schemeRegistry),如下:

 

 

 /**
     * Creates a new AsyncHttpClient.
     *
     * @param schemeRegistry SchemeRegistry to be used
     */
    public AsyncHttpClient(SchemeRegistry schemeRegistry) {

        ……
    }

 

 

可以看到 封装的是DefaultHttpClient类。

 httpClient = new DefaultHttpClient(cm, httpParams);

 

这里面创建了线程池,是用于网络访问子线程操作。

 

 threadPool = getDefaultThreadPool();

 

 

/**
     * Get the default threading pool to be used for this HTTP client.
     *
     * @return The default threading pool to be used
     */
    protected ExecutorService getDefaultThreadPool() {
        return Executors.newCachedThreadPool();
    }

 

 

get、post的执行:

 

 

/**
     * Perform a HTTP GET request and track the Android Context which initiated the request.
     *
     * @param context         the Android Context which initiated the request.
     * @param url             the URL to send the request to.
     * @param params          additional GET parameters to send with the request.
     * @param responseHandler the response handler instance that should handle the response.
     * @return RequestHandle of future request process
     */
    public RequestHandle get(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) {
        return sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(isUrlEncodingEnabled, url, params)), null, responseHandler, context);
    }

 

 

 

 public RequestHandle put(Context context, String url, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) {
        return sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPut(getURI(url)), entity), contentType, responseHandler, context);
    }


get、post封装访问数据的方式不一样,但是都封装成HttpUriRequest 。

 

 

 /**
     * Puts a new request in queue as a new thread in pool to be executed
     *
     * @param client          HttpClient to be used for request, can differ in single requests
     * @param contentType     MIME body type, for POST and PUT requests, may be null
     * @param context         Context of Android application, to hold the reference of request
     * @param httpContext     HttpContext in which the request will be executed
     * @param responseHandler ResponseHandler or its subclass to put the response into
     * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
     *                        HttpPost, HttpGet, HttpPut, etc.
     * @return RequestHandle of future request process
     */
    protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
        ……

        AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context);
        threadPool.submit(request);
        RequestHandle requestHandle = new RequestHandle(request);

        if (context != null) {
            List<RequestHandle> requestList;
            // Add request to request map
            synchronized (requestMap) {
                requestList = requestMap.get(context);
                if (requestList == null) {
                    requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                    requestMap.put(context, requestList);
                }
            }

            requestList.add(requestHandle);

          ……
    }


 AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context);
     threadPool.submit(request);   

具体的网络访问操作封装在AsyncHttpRequest 类里,然后把该对象放在线程池里进行管理。

sendRequest 返回值是RequestHandle ,这个返回值用来做什么呢?

 if (context != null) {
            List<RequestHandle> requestList;
            // Add request to request map
            synchronized (requestMap) {
                requestList = requestMap.get(context);
                if (requestList == null) {
                    requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                    requestMap.put(context, requestList);
                }
            }
            requestList.add(requestHandle);

 

在这里可以看到RequestHandle 对象被放进来了List<RequestHandle>里。

猜测,把RequestHandle 存放起来无非是管理其生命周期,那么启动了就有可能中断,查看List<RequestHandle>的使用,可以看到,该集合主要使用来中断网络访问,

 

  public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) {
        ……


注释说明:

 

 

  * Cancels any pending (or potentially active) requests associated with the passed Context.
     * <p> </p> <b>Note:</b> This will only affect requests which were created with a non-null
     * android Context. This method is intended to be used in the onDestroy method of your android
     * activities to destroy all requests which are no longer required.
     *
     * @param context               the android Context instance associated to the request.
     * @param mayInterruptIfRunning specifies if active requests should be cancelled along with
     *                              pending requests.
     */

取消(终止)所有与该上下文关联的准备中或者已经活跃的请求。

 

 

该方法最后调用

 

  private void cancelRequests(final List<RequestHandle> requestList, final boolean mayInterruptIfRunning) {
        if (requestList != null) {
            for (RequestHandle requestHandle : requestList) {
                requestHandle.cancel(mayInterruptIfRunning);
            }
        }
    }

 

 

 

 

 

由RequestHandle通知AsyncHttpRequest 网络访问中断。

 

 /**
     * Attempts to cancel this request. This attempt will fail if the request has already completed,
     * has already been cancelled, or could not be cancelled for some other reason. If successful,
     * and this request has not started when cancel is called, this request should never run. If the
     * request has already started, then the mayInterruptIfRunning parameter determines whether the
     * thread executing this request should be interrupted in an attempt to stop the request.
     * <p> </p> After this method returns, subsequent calls to isDone() will always return
     * true. Subsequent calls to isCancelled() will always return true if this method returned
     * true. Subsequent calls to isDone() will return true either if the request got cancelled by
     * this method, or if the request completed normally
     *
     * @param mayInterruptIfRunning true if the thread executing this request should be interrupted;
     *                              otherwise, in-progress requests are allowed to complete
     * @return false if the request could not be cancelled, typically because it has already
     * completed normally; true otherwise
     */
    public boolean cancel(final boolean mayInterruptIfRunning) {
        final AsyncHttpRequest _request = request.get();
        if (_request != null) {
           ……
                  _request.cancel(mayInterruptIfRunning);
              
            ……  
              
            } else {
                return _request.cancel(mayInterruptIfRunning);
            }
        }
        return false;
    }

 

 

AsyncHttpRequest  的cancel 方法。

 

  public boolean cancel(boolean mayInterruptIfRunning) {
        isCancelled.set(true);
        request.abort();
        return isCancelled();
    }

 

 

 

看到这里我们已经很清楚地看到整个AsyncHttpClient的模块了,分别是AsyncHttpClient、RequestHandle 和AsyncHttpRequest ,对应的是高层模块的用户操作、回调接口和网络访问执行。

 

接下来我们分别来看看AsyncHttpRequest 和RequestHandle 所封装的内容。

AsyncHttpRequest :

AsyncHttpRequest 对象被submit到threadPool时,便开始run()方法。

 

    @Override
    public void run() {
        if (isCancelled()) {
            return;
        }

        // Carry out pre-processing for this request only once.
        if (!isRequestPreProcessed) {
            isRequestPreProcessed = true;
            onPreProcessRequest(this);
        }

        if (isCancelled()) {
            return;
        }

        responseHandler.sendStartMessage();

        if (isCancelled()) {
            return;
        }

        try {
            makeRequestWithRetries();
        } catch (IOException e) {
            if (!isCancelled()) {
                responseHandler.sendFailureMessage(0, null, null, e);
            } else {
                AsyncHttpClient.log.e("AsyncHttpRequest", "makeRequestWithRetries returned error", e);
            }
        }

        if (isCancelled()) {
            return;
        }

        responseHandler.sendFinishMessage();

        if (isCancelled()) {
            return;
        }

        // Carry out post-processing for this request.
        onPostProcessRequest(this);

        isFinished = true;
    }


其中多次调用isCancelled()方法判断是否已经被中断,

 

 

最后调用到的是。

 

 private void makeRequest() throws IOException {
       ……

        HttpResponse response = client.execute(request, context); <span style="font-family: Arial, Helvetica, sans-serif;">                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 ……                                                                                                                                                                                                                                                                                                    </span>

 

 

 

 

 

 

RequestHandle :

主要是实现了ResponseHandlerInterface接口的子类,对网络访问结果进行解析并封装

 

  // Carry out pre-processing for this response.
        responseHandler.onPreProcessResponse(responseHandler, response);

 

 

 

再通过sendMessage通过主线程网络访问的结果或者中断的情况。

 


 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值