问题
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:
Volleygets instantiated likes this// 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();After sending a GET request I get the response
200with"cache-control"set to"max-age=180, public". So far so good right?- If a GET request gets made twice or more I set
"If-Modified-Since"with the last timestamp the request was made to the request header. - The second time I request a specific API endpoint the sever will respond with a
304.getCacheEntry().datareturnsnullthough. If I check thecache entriesinVolleysRequestQueueI cannot find an entry for my specific request.
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.
回答1:
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
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.
Hope this helps!
来源:https://stackoverflow.com/questions/33606529/volley-cache-returns-null-when-receiving-304