接收304时,Volley Cache返回null [英] Volley Cache returns null when receiving 304
问题描述
我正在尝试使用其Cache
使Volley
正常工作.即使设置了"cache-control"
,当我收到304
时,getCacheEntry().data
仍是null
.这是我在做什么:
I am trying to get Volley
to work using its Cache
. When I receive a 304
getCacheEntry().data
is null
even though "cache-control"
is set. Here is what I am doing:
-
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"
.到目前为止一切都好吗?
After sending a GET request I get the response 200
with "cache-control"
set to "max-age=180, public"
. So far so good right?
我做错了什么?由于某种原因,我有一个请求在被触发一次时总是被缓存.甚至可以返回很多数据.但是不会缓存所有其他请求.以下代码段解析响应并检查304
.
What am I doing wrong? For some reason I have one request that is always cached when fired once. It's even one that returns a lot of data. But all other requests aren't cached. Following code snippet parses the response and checks for 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));
}
}
我真的很感谢对此的任何评论.
I really appreciate any comments on this.
推荐答案
恕我直言,由于以下原因,您的缓存条目始终为null(不仅在获取304 resp代码时):
IMHO, your cache entry is always null (not only when getting 304 resp code), because of the following:
Cache cache = new DiskBasedCache(c.getCacheDir(), 10 * 1024 * 1024); // 10 MB cap
请检查您的c.getCacheDir()
以查看是否要使用外部存储来存储缓存数据,然后应在AndroidManifest.xml
文件中设置WRITE_EXTERNAL_STORAGE
权限.
Please check your c.getCacheDir()
to see if you want to use External Storage to store cache data, then you should set WRITE_EXTERNAL_STORAGE
permission inside AndroidManifest.xml
file.
希望这会有所帮助!
这篇关于接收304时,Volley Cache返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!