Volley源码分析 (三):如何分发结果

来源:互联网 发布:我国网络零售的特点 编辑:程序博客网 时间:2024/05/16 07:06
首先是将请求组装成NetWorkResponse,这里有两种情况,一种是经过网络请求的,一种是取得缓存的,最后统一经过ExecutorDelively。
首先是网络请求:
longrequestStart = SystemClock.elapsedRealtime();
while
( true) {
    HttpResponse httpResponse =
null;
    byte
[] responseContents =null;
   
Map<String , String> responseHeaders =newHashMap<String,String>();
    try
{
       
// Gather headers.
       
Map<String , String> headers = new HashMap<String , String>();
       
addCacheHeaders(headers,request.getCacheEntry());
       
httpResponse = mHttpStack .performRequest(request,headers);
       
StatusLine statusLine = httpResponse.getStatusLine();
        int
statusCode = statusLine.getStatusCode();

       
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
       
// Handle cache validation.
       
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
           
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
                   
request.getCacheEntry().data,responseHeaders, true);
       
}

       
// Some responses such as 204s do not have content.  We must check.
       
if (httpResponse.getEntity() !=null) {
          responseContents = entityToBytes(httpResponse.getEntity())
;
       
} else {
         
// Add 0 byte response as a way of honestly representing a
          // no-content request.
         
responseContents =new byte[0];
       
}

       
// if the request is slow, log it.
       
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
       
logSlowRequests(requestLifetime,request,responseContents,statusLine);

        if
(statusCode < 200 || statusCode > 299 ) {
           
throw new IOException();
       
}
       return newNetworkResponse(statusCode,responseContents,responseHeaders, false );
如果没有修改就传入request的缓存,否则就取response的内容来组成NetWorkResponse;
如果是缓存的就直接在CacheDispather:
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
       
new NetworkResponse(entry.data,entry.responseHeaders));
request.addMarker("cache-hit-parsed");
最后是分发:
// If this request has canceled, finish it and don't deliver.
if(mRequest.isCanceled()) {
   
mRequest .finish("canceled-at-delivery");
    return;
}

// Deliver a normal response or error, depending.
if(mResponse.isSuccess()) {
   
mRequest .deliverResponse(mResponse.result);
}else{
   
mRequest .deliverError(mResponse.error);
}

// If this is an intermediate response, add a marker, otherwise we're done
// and the request can be finished.
if(mResponse.intermediate) {
   
mRequest .addMarker("intermediate-response");
}else{
   
mRequest .finish("done");
}

// If we have been provided a post-delivery runnable, run it.
if(mRunnable!=null) {
   
mRunnable .run();
}
如果请求取消了就直接finish,如果成功了,就交给自己重写的listener,如果是需要再请求的,用于这个请求是不需要立即刷新,但可以立即返回缓存结果,之后再刷新的。这也是上篇讲的内容。
0 0