我正在尝试使用httpResponseCache来缓存我的一些请求。问题是,在发出请求之前,我想知道请求是否被缓存。
我在HttpResponseCache的源代码中看到有一个get方法,它接受(URI,requestMethod,Map<字符串,List<字符串> >)并返回一个cachedResponse。我已经尝试了几组不同的(URI," get ",Headers),但我似乎不能确定headers是什么,并且每次我使用get请求cachedResponse时,我都会返回null,即使有一个响应被缓存。
有没有人成功地使用get方法在发出请求之前确定请求是否被缓存/或者在发出请求之前是否有不同的方法来检查是否有东西被缓存?我知道我可以使用hitCount来判断响应是否是从缓存中获取的,并且我可以使用" cache -Control“、"only- if - cached”来强制缓存响应。我只是希望能够检查它是否被缓存。
下面是我用来实现这一点的一些代码。在活动的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();
}对不起/谢谢/非常感谢您的帮助!
发布于 2014-11-19 17:01:33
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields());这是应该怎么做的,但我还没有尝试过。
https://stackoverflow.com/questions/26241575
复制相似问题