【问题标题】:Volley Cache returns null when receiving 304Volley Cache 收到 304 时返回 null
【发布时间】:2016-02-09 22:41:46
【问题描述】:

我正在尝试让Volley 使用其Cache 工作。当我收到 304 getCacheEntry().datanull 即使 "cache-control" 设置。这是我正在做的事情:

  1. 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();
    
  2. 发送 GET 请求后,我得到了响应 200,其中 "cache-control" 设置为 "max-age=180, public"。到目前为止还不错吧?

  3. 如果 GET 请求被发出两次或更多次,我将 "If-Modified-Since" 设置为对请求标头发出请求的最后一个时间戳。
  4. 当我第二次请求特定 API 端点时,服务器将响应 304getCacheEntry().data 虽然返回 null。如果我检查 Volleys RequestQueue 中的 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,您可以先在CacheDispatcherrun 内的Cache.Entry entry = mCache.get(request.getCacheKey()); 设置断点,看看它是否为空,此行将在您从服务器获得304 之前运行

标签: android caching android-volley android-networking


【解决方案1】:

恕我直言,您的缓存条目始终为空(不仅在获取 304 响应代码时),原因如下:

Cache cache = new DiskBasedCache(c.getCacheDir(), 10 * 1024 * 1024); // 10 MB cap

请检查您的c.getCacheDir() 是否要使用外部存储来存储缓存数据,然后您应该在AndroidManifest.xml 文件中设置WRITE_EXTERNAL_STORAGE 权限。

希望这会有所帮助!

【讨论】:

  • 我解决了这个问题! WRITE_EXTERNAL_STORAGE 设置在 AndroidManifest.xml 中。但是在一些旧的遗留类中,我们出于某种奇怪的原因生成了一个新的RequestQueue……现在它正在工作。谢谢你的帮助!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多