我正在尝试使用 HttpResponseCache 来缓存使用 HttpURLConnection 发送的每个 HTTP 请求。
但即使请求第二次到达资源,命中计数也始终为零。为什么它没有命中缓存?
命中数:
import android.net.http.HttpResponseCache;
...
HttpResponseCache.getInstalled().getHitCount()
用法:
for(byte i = 0; i < 2; i++){
// Cache-Control:max-age=300
HttpURLConnection conn = (HttpURLConnection) new URL("http://redbot.org/").openConnection();
conn.setUseCaches(true);
if(i == 1){
try {
conn.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = conn.getInputStream();
// the resource was cached! show it
Log.i(TAG, "cached");
} catch (FileNotFoundException e) {
// the resource was not cached
Log.i(TAG, "NOT cached");
}
}
}
这就是我启用缓存的方式:
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);