缓存HTTP响应(HttpResponseCache)

时间:2014-01-17 14:43:53

标签: android http caching httpresponsecache

我正在尝试使用HttpResponseCache来缓存使用HttpURLConnection发送的每个HTTP请求。
但即使请求进入资源2次,命中计数总是等于零。为什么它没有达到缓存?

命中数:

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);

0 个答案:

没有答案