天天看點

Android常用開源網絡架構(一)—— Volley篇

在Android開發中,網絡請求是最重要的子產品之一,Android中大部分網絡請求使用的是HTTP連接配接,包括原生的HttpClient和HttpUrlConnection兩種通路網絡方式。需要注意的是,HttpClient方式在Android6.0以後,很多類已經不支援了。

目前主流的開源網絡架構,主要有OkHttp,Volley,Retrofit三種,我本人在短暫的開發經曆中基本也隻接觸過這幾個,在此簡單分析這三個架構,僅作為本人記錄。

Volley架構

Volley架構是由Google在2013年釋出的較為輕量級的網絡架構,主要适用于處理請求次數較多,量級較小的網絡請求。

一、Volley使用方式

Volley的使用方式十分簡單,主要分為以下幾步:

Step1: 引入Volley(Android Studio)

方法一:在項目的build.gradle 添加依賴

方法二:引入volley.jar包

方法三:通過git下載下傳volley包,之後添加為項目的module,并為主工程添加依賴

需要注意的是,如果Volley傳回Object,需要對其進行解析,轉換為Gson對象,那麼還需要引入Gson依賴

注:引入的版本根據sdk版本而定

Step2: 建立請求隊列執行個體

一般而言,請求隊列不需要每次進行網絡請求時建立,通常一個Activity建立一個,或者對于較少請求的輕量級的應用,也可以一個應用隻建立一個請求隊列,主要視請求的多少而定。

Step3: 建立請求Request

Volley本身已封裝好幾種常用的Request,包括StringRequest,JsonRequest,JsonObjectRequest,JsonArrayRequest

值得一提的是,Volley封裝了ImageLoader和ImageRequest,可以友善地支援圖檔的擷取和加載,不需要額外自己添加圖檔的加載

以StringRequest為例,建立Request的代碼也十分簡單:

StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
      @Override
      public void onResponse(String response) {
        Log.e("xxxx", "onStringResponse: " + response);
      }
    }, new ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
        Log.e("xxxx", "onStringErrorResponse: " + error);
      }
    });
           

Step4: 将請求加入請求隊列

經過以上幾個步驟,就可以實作網絡請求,成功和失敗結果均傳回。

二、Volley源碼分析

Volley作為一個輕量級的網絡架構,源碼實際上并不複雜,接下來将針對其主要的代碼進行分析。

1. Volley.java 的主要代碼分析

圖中截出的就是我們在使用Volley時的第一步建立請求隊列的代碼,事實上Volley檔案中也隻有這一個重要的函數,主要步驟如下:

public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

        String userAgent = "volley/0";
        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (NameNotFoundException e) {
        }

        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork(stack);
        
        RequestQueue queue;
        if (maxDiskCacheBytes <= -1)
        {
        	// No maximum size specified
        	queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        }
        else
        {
        	// Disk cache size specified
        	queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
        }

        queue.start();

        return queue;
    }
           
  • 建立了一個用于存儲Volley緩存的檔案,使用的是預設的緩存路徑,然後擷取包名、包的資訊以及使用者資訊等
  • 根據sdk版本,sdk版本大于等于9的,即Android系統2.3版本以上,建立HurlStack,9以下建立HttpClientStack
  • 建立了請求隊列,maxDiskCacheBytes指的是緩存的最大容量,在建立隊列時如果定義了該參數,則按指定的容量,否則緩存容量為按照預設的-1
  • RequestQueue.start()

2. RequestQueue的代碼分析部分

RequestQueue最重要的是add和start兩個函數。

start函數:

/**
     * Starts the dispatchers in this queue.
     */
    public void start() {
        stop();  // Make sure any currently running dispatchers are stopped.
        // Create the cache dispatcher and start it.
        mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
        mCacheDispatcher.start();

        // Create network dispatchers (and corresponding threads) up to the pool size.
        for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }

           

可以看到主要的步驟是建立并啟動了兩種分發器,其中mNetworkDispatchers包含多個NetworkDispatcher,數量預設為4。

add函數的主要代碼如圖所示:

/**
     * Adds a Request to the dispatch queue.
     * @param request The request to service
     * @return The passed-in request
     */
    public <T> Request<T> add(Request<T> request) {
        // Tag the request as belonging to this queue and add it to the set of current requests.
        request.setRequestQueue(this);
        synchronized (mCurrentRequests) {
            mCurrentRequests.add(request);
        }

        // Process requests in the order they are added.
        request.setSequence(getSequenceNumber());
        request.addMarker("add-to-queue");

        // If the request is uncacheable, skip the cache queue and go straight to the network.
        if (!request.shouldCache()) {
            mNetworkQueue.add(request);
            return request;
        }

        // Insert request into stage if there's already a request with the same cache key in flight.
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            if (mWaitingRequests.containsKey(cacheKey)) {
                // There is already a request in flight. Queue up.
                Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
                if (stagedRequests == null) {
                    stagedRequests = new LinkedList<Request<?>>();
                }
                stagedRequests.add(request);
                mWaitingRequests.put(cacheKey, stagedRequests);
                if (VolleyLog.DEBUG) {
                    VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
                }
            } else {
                // Insert 'null' queue for this cacheKey, indicating there is now a request in
                // flight.
                mWaitingRequests.put(cacheKey, null);
                mCacheQueue.add(request);
            }
            return request;
        }
    }
           
  • 将要add的請求加入目前請求的清單,并設定一個序列号碼和一個已加入隊列的tag,用來讓分發器按請求的順序處理請求。
  • 如果請求設定了不緩存(預設是緩存),那麼将其加入網絡請求隊列。
  • 用cachekey來作為請求的唯一辨別,如果有相同key的請求在waitingRequests中,辨別有相同的請求已經執行并且還沒有傳回結果,為避免重複請求,則将該請求存入;如果沒有,則将該請求加入緩存隊列中。

3. CacheDispatcher 和 NetworkDispatcher

在RequestQueue的代碼分析中,我們可以看到隊列并沒有對網絡請求進行處理,接下來我們看看這兩個分發器是如何處理加入隊列的網絡請求的。

① CacheDispatcher

run()函數解析:

@Override
    public void run() {
        if (DEBUG) VolleyLog.v("start new dispatcher");
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

        // Make a blocking call to initialize the cache.
        mCache.initialize();

        Request<?> request;
        while (true) {
        	...
        }
    }
           
  • 設定線程的優先級為最高,并初始化緩存
  • 接下來進入一個無限循環,按序取出清單中的request,對request隊列中的每一個request進行處理

對request進行處理的步驟:

// release previous request object to avoid leaking request object when mQueue is drained.
            request = null;
            try {
                // Take a request from the queue.
                request = mCacheQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }
            try {
                request.addMarker("cache-queue-take");

                // If the request has been canceled, don't bother dispatching it.
                if (request.isCanceled()) {
                    request.finish("cache-discard-canceled");
                    continue;
                }

                // Attempt to retrieve this item from cache.
                Cache.Entry entry = mCache.get(request.getCacheKey());
                if (entry == null) {
                    request.addMarker("cache-miss");
                    // Cache miss; send off to the network dispatcher.
                    mNetworkQueue.put(request);
                    continue;
                }

                // If it is completely expired, just send it to the network.
                if (entry.isExpired()) {
                    request.addMarker("cache-hit-expired");
                    request.setCacheEntry(entry);
                    mNetworkQueue.put(request);
                    continue;
                }

                // We have a cache hit; parse its data for delivery back to the request.
                request.addMarker("cache-hit");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");

                if (!entry.refreshNeeded()) {
                    // Completely unexpired cache hit. Just deliver the response.
                    mDelivery.postResponse(request, response);
                } else {
                    // Soft-expired cache hit. We can deliver the cached response,
                    // but we need to also send the request to the network for
                    // refreshing.
                    request.addMarker("cache-hit-refresh-needed");
                    request.setCacheEntry(entry);

                    // Mark the response as intermediate.
                    response.intermediate = true;

                    // Post the intermediate response back to the user and have
                    // the delivery then forward the request along to the network.
                    final Request<?> finalRequest = request;
                    mDelivery.postResponse(request, response, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mNetworkQueue.put(finalRequest);
                            } catch (InterruptedException e) {
                                // Not much we can do about this.
                            }
                        }
                    });
                }
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
            }
        }
           
  • 從請求清單中取出request,判斷是否已取消,如未取消,則通過request的cacheKey從緩存中擷取
  • 如果緩存中沒有對應key的request或者已經過期,則将該request發送到mNetworkQueue,等待NetworkDispatcher進行處理
  • 如果有對應的緩存request,并且沒有過期,那麼CacheDispatcher會将該請求發送到主線程(發送到主線程的具體方法後面會說明)。
② NetworkDispatcher

同樣,NetworkDispatcher的run()函數也有一個無限循環對request進行處理,在确認request未被中斷(通常發生在請求逾時的情況)并且未被取消後,進行處理。

@Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request<?> request;
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            // release previous request object to avoid leaking request object when mQueue is drained.
            request = null;
            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) {
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                VolleyError volleyError = new VolleyError(e);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                mDelivery.postError(request, volleyError);
            }
        }
    }
           
  • 取出request後,通過Network的performRequest請求網絡
  • 在擷取到response後,通過parseNetworkResponse對response進行解析
  • 如果request需要緩存,則存儲到mCache中,等待CacheDispatcher進行處理
  • 最後将擷取到的response傳回給主線程并标記request完成即可

4. NetworkDispatcher 請求網絡方式

上面run函數中可以看到請求網絡是通過mNetwork.performRequest函數請求網絡,該函數在BasicNetwork中實作,實作方式如下圖:

@Override
    public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            Map<String, String> responseHeaders = Collections.emptyMap();
            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) {

                    Entry entry = request.getCacheEntry();
                    if (entry == null) {
                        return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null,
                                responseHeaders, true,
                                SystemClock.elapsedRealtime() - requestStart);
                    }

                    // A HTTP 304 response does not have all header fields. We
                    // have to use the header fields from the cache entry plus
                    // the new ones from the response.
                    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                    entry.responseHeaders.putAll(responseHeaders);
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data,
                            entry.responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }
                ...
            } catch (SocketTimeoutException e) {
                attemptRetryOnException("socket", request, new TimeoutError());
            } catch (ConnectTimeoutException e) {
                attemptRetryOnException("connection", request, new TimeoutError());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Bad URL " + request.getUrl(), e);
            } catch (IOException e) {
                int statusCode = 0;
                NetworkResponse networkResponse = null;
                if (httpResponse != null) {
                    statusCode = httpResponse.getStatusLine().getStatusCode();
                } else {
                    throw new NoConnectionError(e);
                }
                if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || 
                		statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                	VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl());
                } else {
                	VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
                }
                if (responseContents != null) {
                    networkResponse = new NetworkResponse(statusCode, responseContents,
                            responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
                            statusCode == HttpStatus.SC_FORBIDDEN) {
                        attemptRetryOnException("auth",
                                request, new AuthFailureError(networkResponse));
                    } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || 
                    			statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                        attemptRetryOnException("redirect",
                                request, new RedirectError(networkResponse));
                    } else {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(e);
                }
            }
        }
    }
           
  • 擷取headers,之後通過mHttpStack請求網絡
  • mHttpStack也是一個接口類,通過之前提到過的HurlStack和HttpClientStack實作
  • 擷取到 httpResponse後,根據響應的狀态碼,傳回不同的NetworkResponse給NetworkDispatcher

5. 傳回response給主線程的方式

在請求網絡擷取到NetworkResponse後,通過mDeliver.postResponse将結果傳回給主線程,代碼如下圖:

@Override
    public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    }
           

ResponseRunnable代碼:

@SuppressWarnings("unchecked")
        @Override
        public void run() {
            // 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();
            }
       }
           

根據Request請求的結果,Runnable分别調用了Request不同的函數。

以StringRequest為例:

@Override
    protected void deliverResponse(String response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }

           

請求成功時調用mListener(建立StringRequest時的參數)的回調函數,在回調函數中對擷取到的response進行需要的操作即可。

至此,Volley實作網絡請求的基本流程就梳理完成了,最後再通過流程圖進行總結:

Android常用開源網絡架構(一)—— Volley篇

對Volley架構的總結就到這裡,下一篇将繼續總結另一種重要的網絡架構——OkHttp的相關内容。