2014-10-07 54 views
2

我正在尝试使用httpResponseCache来缓存我的一些请求。问题是,我想知道请求是否在请求之前被缓存。使用HttpResponseCache.get时需要使用什么头文件

我在源文件中看到HttpResponseCache有一个get方法(URI,requestMethod,Map < String,List < String >>)并返回一个cachedResponse。我已经尝试了几组不同的(URI,“GET”,Headers),但我似乎无法弄清楚标题是什么,每次我使用get请求一个cachedResponse时,我都会返回null,甚至虽然有缓存的响应。

有没有人成功地使用get方法来确定请求是否在做出请求之前被缓存/或者有其他方法来检查在请求之前是否缓存了某些内容?我知道我可以使用hitCount来确定响应是否来自缓存,并且我可以使用“缓存控制”,“仅缓存”来强制缓存响应。我只想能够检查它是否被缓存。

下面是我用来试图完成这个的一些代码。在活动的OnCreate,我不初始化缓存是这样的:

try { 
       File httpCacheDir = new File(this.getCacheDir(), "http"); 
       long httpCacheSize = 10 * 1024 * 1024; // 10 MiB 
       Class.forName("android.net.http.HttpResponseCache") 
         .getMethod("install", File.class, long.class) 
         .invoke(null, httpCacheDir, httpCacheSize); 
     } 
      catch (Exception httpResponseCacheNotAvailable) { 
       Log.d(TAG,"HttpResponseCache not available."); 
      } 

,然后尝试使用这种方式:

HttpResponseCache cache = HttpResponseCache.getInstalled(); 
      try { 
       HashMap map = new HashMap<String, List<String>>(); 
       CacheResponse response = cache.get(URI.create(base_url), "GET", map); 
       //response is always null 
       Log.d(TAG," Response is!:"+response); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

对不起/谢谢/任何帮助是非常感谢!

+0

My ** cache.get **在这里总是返回null。你找到解决方案吗? – 2018-02-15 15:36:22

回答

-1
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
HttpResponseCache cache = HttpResponseCache.getInstalled(); 
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields()); 

这是应该怎么做,但我还没有尝试过。