我正在尝试使用httpResponseCache来缓存我的一些请求。问题是,我想知道在发出请求之前是否缓存了请求。
我在HttpResponseCache的源代码中看到有一个get方法接受(URI,requestMethod,Map< String,List< String>>)并返回一个cachedResponse。我已经尝试了几组不同的(URI,“GET”,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();
}
对不起/谢谢/任何帮助都非常感谢!
答案 0 :(得分:-1)
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields());
应该怎么做,但我还没有尝试过。