我正在嘗試使用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();
}
對不起/謝謝/任何幫助是非常感謝!
My ** cache.get **在這裏總是返回null。你找到解決方案嗎? – 2018-02-15 15:36:22