2015-11-09 79 views
2

时返回null,我试图让Volley利用其Cache工作。当我收到304getCacheEntry().datanull即使"cache-control"已设置。下面是我在做什么:凌空缓存接收304

  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请求后,我得到"cache-control"设置为"max-age=180, public"响应200。到目前为止这么好吗?

  3. 如果获得GET请求两次或更多,我设置了"If-Modified-Since"以及最后一次请求标头的时间戳。
  4. 我第二次请求特定的API端点时,服务器将以304响应。 getCacheEntry().data返回null虽然。如果我检查cache entriesVolleysRequestQueue我无法找到我的具体请求条目。

我在做什么错?出于某种原因,我有一个请求在启动时总是被缓存。它甚至可以返回大量数据。但所有其他请求都没有被缓存。以下代码段解析响应并检查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)); 
    } 
} 

我真的很感激任何意见。

+0

如果您的请求是POST请求,IMO您可以阅读以下内容http://stackoverflow.com/questions/21953519/volley-exception-error-when-response-code-304-and-200 – BNK

+0

Thanks @BNK这是一个GET请求,虽然 – Ben

+0

如果服务器在互联网上发布,请发布的URL,以便我可以检查明天 – BNK

回答

0

恕我直言,(获得304 RESP代码不仅当),因为你的缓存条目总是空如下:

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

请检查您c.getCacheDir()看到,如果你想使用外部存储器来存储缓存数据,那么你应该在AndroidManifest.xml文件里设置WRITE_EXTERNAL_STORAGE权限。

希望这会有所帮助!

+0

我解决了这个问题! 'WRITE_EXTERNAL_STORAGE'在'AndroidManifest.xml'中设置。但是在一些旧的遗留类中,我们由于某种奇怪的原因生成了一个新的RequestQueue ......现在它正在工作。感谢您的帮助!! – Ben