1. 程式人生 > >Android常用開源網路框架(一)—— Volley篇

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 新增依賴

implementation 'com.mcxiaoke.volley:library:1.0.+'

方法二:引入volley.jar包

方法三:通過git下載volley包,之後新增為專案的module,併為主工程新增依賴

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

implementation 'com.google.code.gson:gson:2.8.2'

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

Step2: 建立請求佇列例項

requestQueue = Volley.newRequestQueue(context); 

一般而言,請求佇列不需要每次進行網路請求時建立,通常一個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: 將請求加入請求佇列

 requestQueue.add(stringRequest);

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

二、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)