Volley Cache returns null when receiving 304

心已入冬 提交于 2019-12-11 03:26:40

问题


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:

  1. Volley gets 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();
    
  2. After sending a GET request I get the response 200 with "cache-control" set to "max-age=180, public". So far so good right?

  3. 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.
  4. The second time I request a specific API endpoint the sever will respond with a 304. getCacheEntry().data returns null though. If I check the cache entries in Volleys RequestQueue I 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!