【发布时间】:2016-02-09 22:41:46
【问题描述】:
我正在尝试让Volley 使用其Cache 工作。当我收到 304 getCacheEntry().data 是 null 即使 "cache-control" 设置。这是我正在做的事情:
-
Volley像这样被实例化// Instantiate the cache Cache cache = new DiskBasedCache(c.getCacheDir(), 10 * 1024 * 1024); // 10 MB cap // Set up the network to use HttpURLConnection as the HTTP client. Network network = new BasicNetwork(new HurlStack()); // Instantiate the RequestQueue with the cache and network. mRequestQueue = new RequestQueue(cache, network); // Start the queue mRequestQueue.start(); 发送 GET 请求后,我得到了响应
200,其中"cache-control"设置为"max-age=180, public"。到目前为止还不错吧?- 如果 GET 请求被发出两次或更多次,我将
"If-Modified-Since"设置为对请求标头发出请求的最后一个时间戳。 - 当我第二次请求特定 API 端点时,服务器将响应
304。getCacheEntry().data虽然返回null。如果我检查VolleysRequestQueue中的cache entries,我找不到我的特定请求的条目。
我做错了什么?出于某种原因,我有一个请求在触发一次时总是被缓存。它甚至可以返回大量数据。但所有其他请求都不会被缓存。以下代码 sn-p 解析响应并检查 304。
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response, String charset) {
try {
String json = "";
if (!response.notModified) {
json = new String(response.data, charset);
} else {
//if not modified -> strangely getCacheEntry().data always null
json = new String(getCacheEntry().data, charset);
}
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
我真的很感谢任何关于此的 cmets。
【问题讨论】:
-
如果您的请求是 POST 请求,IMO 您可以阅读以下内容stackoverflow.com/questions/21953519/…
-
感谢@BNK,虽然这是一个 GET 请求
-
如果服务器是在互联网上发布的,请把网址贴出来,以便我明天查看
-
IMO,您可以先在
CacheDispatcher的run内的Cache.Entry entry = mCache.get(request.getCacheKey());设置断点,看看它是否为空,此行将在您从服务器获得304 之前运行
标签: android caching android-volley android-networking