Volley源碼解析

Volley的優(yōu)缺點(diǎn)

優(yōu)點(diǎn)

  • 自動(dòng)的調(diào)度網(wǎng)絡(luò)請(qǐng)求
  • 多并發(fā)的網(wǎng)絡(luò)請(qǐng)求
  • 可以緩存http請(qǐng)求
  • 支持請(qǐng)求的優(yōu)先級(jí)
  • 支持取消請(qǐng)求的API缸逃,可以取消單個(gè)請(qǐng)求,可以設(shè)置取消請(qǐng)求的范圍域瓤狐。
  • 代碼標(biāo)準(zhǔn)化榜配,使開發(fā)者更容易專注于我們的業(yè)務(wù)的邏輯處理
  • 更容易給UI填充來自網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)
  • Volley可以是作為調(diào)試和跟蹤的工具(用起來特別爽~)

缺點(diǎn)

  • 使用的是httpclient、HttpURLConnection
  • 6.0不支持httpclient了盖袭,如果想支持得添加org.apache.http.legacy.jar
  • 非常不適合大的文件流操作,例如上傳和下載彼宠。因?yàn)閂olley會(huì)把所有的服務(wù)器端返回的數(shù)據(jù)在解析期間緩存進(jìn)內(nèi)存鳄虱。
  • 只支持http請(qǐng)求
  • 圖片加載性能一般

Volley的工作原理

Volley工作流程.png

源碼解析
下面開始Volley源碼解析,為了方便理解凭峡,我們按照Volley的實(shí)際開發(fā)使用流程來分析其源碼拙已。
(1)初始化RequestQueue

  • 按照Volley的使用方法,我們最先開始要初始化一個(gè)RequestQueue摧冀,由于新建一個(gè)RequestQueue非常消耗資源倍踪,開發(fā)的時(shí)候只需創(chuàng)建一次即可
   RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
  • 接著會(huì)執(zhí)行Volley這個(gè)類的newRequestQueue方法
  public static RequestQueue newRequestQueue(Context context, BaseHttpStack stack) {
        BasicNetwork network;
        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                network = new BasicNetwork(new HurlStack());
            } else {
                String userAgent = "volley/0";
                try {
                    String packageName = context.getPackageName();
                    PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
                    userAgent = packageName + "/" + info.versionCode;
                } catch (NameNotFoundException e) {
                }

                network = new BasicNetwork(
                        new HttpClientStack(AndroidHttpClient.newInstance(userAgent)));
            }
        } else {
            network = new BasicNetwork(stack);
        }

        return newRequestQueue(context, network);
    }

上面源碼可以看出,如果Android版本大于或等于2.3索昂,則調(diào)用給予HttpURLCollection的HurlStack建车,否則就調(diào)用HttpClient的HttpClientStack,接下來Volley會(huì)創(chuàng)建RequestQueue椒惨,并調(diào)用它的start方法缤至。

   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();
        }
    }

RequestQueue對(duì)象創(chuàng)建的時(shí)候,會(huì)初始化一個(gè)緩存調(diào)度線程(CacheDispatcher)康谆,和4個(gè)網(wǎng)絡(luò)調(diào)度線程(NetworkDispatcher)领斥,所以Volley默認(rèn)會(huì)在后臺(tái)開啟5個(gè)線程。線程都初始化之后沃暗,分別調(diào)用其start方法開啟線程月洛。
(2) 把Request請(qǐng)求添加進(jìn)RequestQueue請(qǐng)求隊(duì)列之后的流程

queue.add(stringRequest);
  • 把 Request請(qǐng)求添加進(jìn)RequestQueue中,首先通過執(zhí)行request.shouldCache()方法判斷request是否應(yīng)該緩存孽锥,默認(rèn)情況下是true嚼黔,也就是所有的請(qǐng)求默認(rèn)都要緩存。如果request不需要緩存的話惜辑,把請(qǐng)求放進(jìn)網(wǎng)絡(luò)請(qǐng)求隊(duì)列隔崎,如果request需要緩存那就放進(jìn)緩存隊(duì)列。
 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;
        }
        mCacheQueue.add(request);
        return request;
     }

** RequestQueue的add方法并沒有進(jìn)行網(wǎng)絡(luò)或?qū)彺娴牟僮髟铣螅?dāng)請(qǐng)求添加金網(wǎng)絡(luò)請(qǐng)求隊(duì)列或者緩存隊(duì)列時(shí)爵卒,在后臺(tái)的網(wǎng)絡(luò)調(diào)度線程和緩存調(diào)度線程會(huì)輪詢各自的請(qǐng)求隊(duì)列,如果發(fā)現(xiàn)請(qǐng)求任務(wù)需要處理則開始執(zhí)行撵彻。下面分別來分析CacheDispatcher和NetworkDispatcher的源碼钓株。**

(3)CacheDispatcher的工作流程

  • CacheDispatcher線程的run方法里是一個(gè)死循環(huán)实牡,并不斷地執(zhí)行processRequest方法
  @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();   while (true) {
        try {
            processRequest();
  } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
  if (mQuit) {
                return;
  }
        }
    }
}
  • CacheDispatcher線程的processRequest方法
    private void processRequest() throws InterruptedException {
        // Get a request from the cache triage queue, blocking until
        // at least one is available.
        final Request<?> request = mCacheQueue.take();
        request.addMarker("cache-queue-take");

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

        // 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.
            if (!mWaitingRequestManager.maybeAddToWaitingRequests(request)) {
                mNetworkQueue.put(request);
            }
            return;
        }

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

        // 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;

            if (!mWaitingRequestManager.maybeAddToWaitingRequests(request)) {
                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
                mDelivery.postResponse(request, response, new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mNetworkQueue.put(request);
                        } catch (InterruptedException e) {
                            // Restore the interrupted status
                            Thread.currentThread().interrupt();
                        }
                    }
                });
            } else {
                // request has been added to list of waiting requests
                // to receive the network response from the first request once it returns.
                mDelivery.postResponse(request, response);
            }
        }
    }

可以發(fā)現(xiàn)該方法如果請(qǐng)求被取消的話,退出該方法轴合;如果請(qǐng)求沒有被取消則判斷請(qǐng)求是否有緩存的響應(yīng)创坞。如果有緩存的響應(yīng)并且沒有過期,則對(duì)緩存響應(yīng)進(jìn)行解析并回調(diào)給主線程受葛;如果沒有緩存的響應(yīng)题涨,則將請(qǐng)求加入網(wǎng)絡(luò)隊(duì)列,接下來看看網(wǎng)絡(luò)調(diào)度線程N(yùn)etworkDispatcher是如何工作的总滩。

(4)NetworkDispatcher的工作流程

  • NetworkDispatcher的run方法同樣也會(huì)執(zhí)行processRequest方法纲堵,如下所示:
   @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            try {
                processRequest();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
            }
        }
    }

processRequest方法如下所示:

 private void processRequest() throws InterruptedException {
        // Take a request from the queue.
        Request<?> request = mQueue.take();

        long startTimeMs = SystemClock.elapsedRealtime();
        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");
                request.notifyListenerResponseNotUsable();
                return;
            }

            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");
                request.notifyListenerResponseNotUsable();
                return;
            }

            // 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);
            request.notifyListenerResponseReceived(response);
        } catch (VolleyError volleyError) {
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            parseAndDeliverNetworkError(request, volleyError);
            request.notifyListenerResponseNotUsable();
        } 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.notifyListenerResponseNotUsable();
        }
    }

網(wǎng)絡(luò)調(diào)度線程也是不斷地從隊(duì)列中取出請(qǐng)求并且判斷該請(qǐng)求是否被取消了。如果該請(qǐng)求沒有被取消闰渔,就去請(qǐng)求網(wǎng)絡(luò)席函,并把網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)回調(diào)回主線程。請(qǐng)求網(wǎng)絡(luò)時(shí)調(diào)用Network的performRequest()方法冈涧,下面看看Network的這個(gè)類的performRequest方法茂附。

  @Override
    public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            List<Header> responseHeaders = Collections.emptyList();
            try {
                // Gather headers.
                Map<String, String> additionalRequestHeaders =
                        getCacheHeaders(request.getCacheEntry());
                httpResponse = mBaseHttpStack.executeRequest(request, additionalRequestHeaders);
                int statusCode = httpResponse.getStatusCode();

                responseHeaders = httpResponse.getHeaders();
                // Handle cache validation.
                if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                    Entry entry = request.getCacheEntry();
                    if (entry == null) {
                        return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, true,
                                SystemClock.elapsedRealtime() - requestStart, responseHeaders);
                    }
                    // Combine cached and response headers so the response will be complete.
                    List<Header> combinedHeaders = combineHeaders(responseHeaders, entry);
                    return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data,
                            true, SystemClock.elapsedRealtime() - requestStart, combinedHeaders);
                }

                // Some responses such as 204s do not have content.  We must check.
                InputStream inputStream = httpResponse.getContent();
                if (inputStream != null) {
                  responseContents =
                          inputStreamToBytes(inputStream, httpResponse.getContentLength());
                } 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, statusCode);

                if (statusCode < 200 || statusCode > 299) {
                    throw new IOException();
                }
                return new NetworkResponse(statusCode, responseContents, false,
                        SystemClock.elapsedRealtime() - requestStart, responseHeaders);
            } catch (SocketTimeoutException e) {
                attemptRetryOnException("socket", request, new TimeoutError());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Bad URL " + request.getUrl(), e);
            } catch (IOException e) {
                int statusCode;
                if (httpResponse != null) {
                    statusCode = httpResponse.getStatusCode();
                } else {
                    throw new NoConnectionError(e);
                }
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
                NetworkResponse networkResponse;
                if (responseContents != null) {
                    networkResponse = new NetworkResponse(statusCode, responseContents, false,
                            SystemClock.elapsedRealtime() - requestStart, responseHeaders);
                    if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED ||
                            statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                        attemptRetryOnException("auth",
                                request, new AuthFailureError(networkResponse));
                    } else if (statusCode >= 400 && statusCode <= 499) {
                        // Don't retry other client errors.
                        throw new ClientError(networkResponse);
                    } else if (statusCode >= 500 && statusCode <= 599) {
                        if (request.shouldRetryServerErrors()) {
                            attemptRetryOnException("server",
                                    request, new ServerError(networkResponse));
                        } else {
                            throw new ServerError(networkResponse);
                        }
                    } else {
                        // 3xx? No reason to retry.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    attemptRetryOnException("network", request, new NetworkError());
                }
            }
        }
    }

可以發(fā)現(xiàn)通過mBaseHttpStack的executeRequest方法返回響應(yīng)的數(shù)據(jù),其實(shí)mBaseHttpStack就是前面提的HulStack和HttpClientStack的父類督弓∮回到NetworkDispatcher請(qǐng)求網(wǎng)絡(luò)后,會(huì)將響應(yīng)結(jié)果存在緩存中愚隧,并調(diào)用下面這段代碼Delivery的postResponse方法溶推。如下所示

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

ResponseDeliveryRunnable里面做了什么:

   @SuppressWarnings("unchecked")
        @Override
        public void run() {
            // NOTE: If cancel() is called off the thread that we're currently running in (by
            // default, the main thread), we cannot guarantee that deliverResponse()/deliverError()
            // won't be called, since it may be canceled after we check isCanceled() but before we
            // deliver the response. Apps concerned about this guarantee must either call cancel()
            // from the same thread or implement their own guarantee about not invoking their
            // listener after cancel() has been called.

            // 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();
            }
       }

上面代碼可以看到如果響應(yīng)成功將會(huì)執(zhí)行Request的deliverResponse方法,并把響應(yīng)結(jié)果傳進(jìn)去奸攻,如果響應(yīng)失敗,就執(zhí)行deliverError方法虱痕,并把響應(yīng)失敗的對(duì)象傳進(jìn)去睹耐。接著我們就看看Request的deliverResponse都干了什么。Request的子類有很多部翘,這里就拿StringRequest來做參考硝训。

  @Override
    protected void deliverResponse(String response) {
        Response.Listener<String> listener;
        synchronized (mLock) {
            listener = mListener;
        }
        if (listener != null) {
            listener.onResponse(response);
        }
    }

錯(cuò)誤的回調(diào)在父類Request中可以找到

   public void deliverError(VolleyError error) {
        Response.ErrorListener listener;
        synchronized (mLock) {
            listener = mErrorListener;
        }
        if (listener != null) {
            listener.onErrorResponse(error);
        }
    }

拿到響應(yīng)結(jié)果之后,如果請(qǐng)求成功則回調(diào)onResponse
新思,如果請(qǐng)求失敗則回調(diào)onErrorResponse窖梁,整個(gè)流程就是這樣了。


源碼中涉及到的一些知識(shí)點(diǎn)

(1)Volley是如何把請(qǐng)求的數(shù)據(jù)回調(diào)回主線程中的夹囚?

使用Handler.postRunnable(Runnable)方法回調(diào)回主線程中進(jìn)行處理纵刘,ExecutorDelivery的構(gòu)造方法中可以看到這段代碼,如下所示:

  public ExecutorDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        mResponsePoster = new Executor() {
            @Override
            public void execute(Runnable command) {
                handler.post(command);
            }
        };
    }

(2)Volley開啟了幾個(gè)后臺(tái)線程荸哟?

總共開啟了5個(gè)線程:1個(gè)緩存調(diào)度線程和4個(gè)網(wǎng)絡(luò)調(diào)度線程假哎,并且線程的優(yōu)先級(jí)為10瞬捕,即后臺(tái)線程。Volley其實(shí)并沒有開啟線程池去維護(hù)線程舵抹,而是硬性地開了5個(gè)線程肪虎,這點(diǎn)我覺得是可以進(jìn)行優(yōu)化的。

 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

(3)Volley進(jìn)行網(wǎng)絡(luò)請(qǐng)求時(shí)用到了Http協(xié)議的哪些字段惧蛹?
響應(yīng)的數(shù)據(jù)解析在HttpHeaderParser類中的parseCacheHeaders方法中可以找到

  public static Cache.Entry parseCacheHeaders(NetworkResponse response) {
        long now = System.currentTimeMillis();

        Map<String, String> headers = response.headers;

        long serverDate = 0;
        long lastModified = 0;
        long serverExpires = 0;
        long softExpire = 0;
        long finalExpire = 0;
        long maxAge = 0;
        long staleWhileRevalidate = 0;
        boolean hasCacheControl = false;
        boolean mustRevalidate = false;

        String serverEtag = null;
        String headerValue;

        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = parseDateAsEpoch(headerValue);
        }

        headerValue = headers.get("Cache-Control");
        if (headerValue != null) {
            hasCacheControl = true;
            String[] tokens = headerValue.split(",");
            for (int i = 0; i < tokens.length; i++) {
                String token = tokens[i].trim();
                if (token.equals("no-cache") || token.equals("no-store")) {
                    return null;
                } else if (token.startsWith("max-age=")) {
                    try {
                        maxAge = Long.parseLong(token.substring(8));
                    } catch (Exception e) {
                    }
                } else if (token.startsWith("stale-while-revalidate=")) {
                    try {
                        staleWhileRevalidate = Long.parseLong(token.substring(23));
                    } catch (Exception e) {
                    }
                } else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
                    mustRevalidate = true;
                }
            }
        }

        headerValue = headers.get("Expires");
        if (headerValue != null) {
            serverExpires = parseDateAsEpoch(headerValue);
        }

        headerValue = headers.get("Last-Modified");
        if (headerValue != null) {
            lastModified = parseDateAsEpoch(headerValue);
        }

        serverEtag = headers.get("ETag");

        // Cache-Control takes precedence over an Expires header, even if both exist and Expires
        // is more restrictive.
        if (hasCacheControl) {
            softExpire = now + maxAge * 1000;
            finalExpire = mustRevalidate
                    ? softExpire
                    : softExpire + staleWhileRevalidate * 1000;
        } else if (serverDate > 0 && serverExpires >= serverDate) {
            // Default semantic for Expire header in HTTP specification is softExpire.
            softExpire = now + (serverExpires - serverDate);
            finalExpire = softExpire;
        }

        Cache.Entry entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = serverEtag;
        entry.softTtl = softExpire;
        entry.ttl = finalExpire;
        entry.serverDate = serverDate;
        entry.lastModified = lastModified;
        entry.responseHeaders = headers;
        entry.allResponseHeaders = response.allHeaders;

        return entry;
    }

用到的Http協(xié)議的字段如下:

  • Date:返回服務(wù)器時(shí)間扇救,如果想得到服務(wù)器的時(shí)候,我們可以從這里獲取

  • Cache-Control:為no-cache和no-store:不緩存響應(yīng)數(shù)據(jù)香嗓,如果需要緩存響應(yīng)數(shù)據(jù)迅腔,當(dāng)需要設(shè)置緩存時(shí),通過maxAge的值來設(shè)置緩存過期的時(shí)間陶缺。

  • Must-revalidate和proxy-revalidate:該值為一個(gè)boolean值钾挟,服務(wù)器告訴客戶端,緩存數(shù)據(jù)過期前饱岸,可以使用緩存掺出;緩存一旦過期,必須去源服務(wù)器進(jìn)行有效性校驗(yàn)苫费。

  • Expires:設(shè)置緩存過期的時(shí)間汤锨,如果 Cache-Control設(shè)置為需要緩存,那么優(yōu)先以 Cache-Control的maxAge的值來設(shè)置緩存過期時(shí)間百框。

  • Last-Modified:在瀏覽器第一次請(qǐng)求某一個(gè)URL時(shí)闲礼,服務(wù)器端的返回狀態(tài)會(huì)是200,內(nèi)容是客戶端請(qǐng)求的資源铐维,同時(shí)有一個(gè)Last-Modified的屬性標(biāo)記此文件在服務(wù)器端最后被修改的時(shí)間柬泽。
    客戶端第二次請(qǐng)求此URL時(shí),根據(jù)HTTP協(xié)議的規(guī)定嫁蛇,瀏覽器會(huì)向服務(wù)器傳送If-Modified-Since報(bào)頭锨并,詢問該時(shí)間之后文件是否有被修改過,如果服務(wù)器端的資源沒有變化睬棚,則自動(dòng)返回 HTTP 304(Not Changed.)狀態(tài)碼第煮,內(nèi)容為空,這樣就節(jié)省了傳輸數(shù)據(jù)量抑党。它和請(qǐng)求頭的if-modified-since字段去判斷資源有沒有被修改的包警。

  • ETags:它和if-None-Match(HTTP協(xié)議規(guī)格說明定義ETag為“被請(qǐng)求變量的實(shí)體值”,或者是一個(gè)可以與Web資源關(guān)聯(lián)的記號(hào))常用來判斷當(dāng)前請(qǐng)求資源是否改變底靠。類似于Last-Modified和HTTP-IF-MODIFIED-SINCE害晦。但是有所不同的是Last-Modified和HTTP-IF-MODIFIED-SINCE只判斷資源的最后修改時(shí)間,而ETags和If-None-Match可以是資源任何的任何屬性暑中,不如資源的MD5等篱瞎。

關(guān)于Volley的其它用法苟呐,可以參照我之前寫的幾篇文章
Volley的基本使用方法
Volley的封裝
那些年我使用Volley遇到的坑

好的就這些了,如果對(duì)你有用記得點(diǎn)個(gè)贊表示小小的鼓勵(lì)一下俐筋。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末牵素,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子澄者,更是在濱河造成了極大的恐慌笆呆,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粱挡,死亡現(xiàn)場(chǎng)離奇詭異赠幕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)询筏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門榕堰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人嫌套,你說我怎么就攤上這事逆屡。” “怎么了踱讨?”我有些...
    開封第一講書人閱讀 157,921評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵魏蔗,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我痹筛,道長(zhǎng)莺治,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,648評(píng)論 1 284
  • 正文 為了忘掉前任帚稠,我火速辦了婚禮谣旁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘滋早。我一直安慰自己榄审,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評(píng)論 6 386
  • 文/花漫 我一把揭開白布馆衔。 她就那樣靜靜地躺著,像睡著了一般怨绣。 火紅的嫁衣襯著肌膚如雪角溃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評(píng)論 1 291
  • 那天篮撑,我揣著相機(jī)與錄音减细,去河邊找鬼。 笑死赢笨,一個(gè)胖子當(dāng)著我的面吹牛未蝌,可吹牛的內(nèi)容都是我干的驮吱。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼萧吠,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼左冬!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起纸型,我...
    開封第一講書人閱讀 37,817評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤拇砰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后狰腌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體除破,經(jīng)...
    沈念sama閱讀 44,275評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評(píng)論 2 327
  • 正文 我和宋清朗相戀三年琼腔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瑰枫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,724評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡丹莲,死狀恐怖光坝,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情圾笨,我是刑警寧澤教馆,帶...
    沈念sama閱讀 34,409評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站擂达,受9級(jí)特大地震影響土铺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜板鬓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評(píng)論 3 316
  • 文/蒙蒙 一悲敷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧俭令,春花似錦后德、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至赫蛇,卻和暖如春绵患,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背悟耘。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評(píng)論 1 266
  • 我被黑心中介騙來泰國打工落蝙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,503評(píng)論 2 361
  • 正文 我出身青樓筏勒,卻偏偏與公主長(zhǎng)得像移迫,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子管行,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評(píng)論 2 350