排球请求机制

时间:2016-06-11 12:40:14

标签: android android-volley

我正在使用此link

阅读有关Volley Library的内容

它说"首先,Volley检查请求是否可以从缓存中提供服务。如果可以,则读取,解析和传递缓存的响应。否则将传递给网络线程。"

所以我的问题是假设凌空击中了一些网址并且网络在中间下来然后在下一个请求中如何知道它是否必须从缓存中获取数据或者需要将请求传递给网络线程?

1 个答案:

答案 0 :(得分:1)

当您运行应用程序时,第一个请求发送到网址,Volley还会检查该网址的缓存条目是否存在。如果是,并且它有效(未过期),Volley将从缓存到响应。否则,它将传递给网络线程。获取响应数据时,它将解析响应标头以查看是否可以缓存数据。 然后使用同一网址的第二个请求,虽然网络是否可用,但是网络服务是否可用,如果该网址的缓存条目存在且有效,则缓存数据将用于响应。

您可以在CacheDispatcher.java file

中找到更多详情
...
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");
    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");
...

以及HttpHeaderParser.java file内的parseCacheHeaders

如果Web服务器不支持缓存输出,您可以在以下问题中为Volley实现缓存:

  

Android Setup Volley to use from Cache

希望它有所帮助!

相关问题