[Android]Volley源代碼分析(叄)Network

假設各位看官細緻看過我以前的文章,實際上Network這塊的僅僅是點小功能的補充。咱們來看下NetworkDispatcher的核心處理邏輯:java

<span style="font-size:18px;">while (true) {
            try {
                // Take a request from the queue.
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }

            try {
                request.addMarker("network-queue-take");

                // If the request was cancelled already, do not perform the
                // network request.
                if (request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                    continue;
                }

                addTrafficStatsTag(request);

                // Perform the network request.
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");

                // If the server returned 304 AND we delivered a response already,
                // we're done -- don't deliver a second identical response.
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish("not-modified");
                    continue;
                }

                // Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");

                // Write to cache if applicable.
                // TODO: Only update cache metadata instead of entire record for 304s.
                if (request.shouldCache() && response.cacheEntry != null) {
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }

                // Post the response back.
                request.markDelivered();
                mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }</span>
     咱們看到NetworkDispatcher和CacheDispatcher的差異在於
<span style="font-size:18px;">                addTrafficStatsTag(request);

                // Perform the network request.
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");</span>
addTrafficStatsTag(request);方法用來優化網絡通道,並不屬於咱們聊的重點。咱們知道mNetwork經過HttpStack來實現網絡請求,咱們先來看一下HurlStack。

<span style="font-size:18px;">@Override
    public HttpResponse performRequest(Request<?

> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }</span>api


      HurlStack是經過HttpUrlConnection的方式來請求數據。同一時候,它也聽過了接口 UrlRewriter mUrlRewriter;來實現url的重定向。HurlStack返回了HttpResponse給上層NetworkDispatcher.HttpClientStack大同小異咱們就不看了。固然咱們也看出了CacheDispatcher和NetworkDispatcher代碼上的不足,但是都是些小瑕疵。因爲對於Request.isCancel這些方面的推斷全然可以採用模板方法的方式來統一。

     NetworkDispatcher經過Network取得HttpResponse以後依然跟CacheDispacher同樣用Request進行包裝:網絡

<span style="font-size:18px;"><span style="font-size:18px;">Response<?> response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");</span></span>
    最後推斷Request是否需要Cache假設需要就放到Cache緩衝池裏面:

<span style="font-size:18px;">if (request.shouldCache() && response.cacheEntry != null) {
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }</span>
   那麼NetworkDispatcher的基本流程就走完了。下一章,咱們將針對Volley提供給咱們方便api結合源代碼來看待Volley.
相關文章
相關標籤/搜索