我一直在我的应用程序中成功使用 HttpResponseCache,但是当我的手机更新到 Lollipop 时,我意识到 HttpResponseCache 现在永远不会被“命中”,总是做网络请求。我已经确认在 Android 版本中,Lollipop 之前的版本仍然运行良好。也许这是我做错了,随着新的 Android 变化它已经出现了。
有人知道吗?
我的代码:
应用程序类,onCreate...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir()
, "http");
long httpCacheSize = 10 * 1024 * 1024;
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Log.i(TAG, "HTTP response cache installation failed:" + e);
}
} else {
try {
File httpCacheDir = new File(getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024;
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
} catch (Exception e) {
Log.i(TAG, "HTTP response cache installation failed:" +
}
}
管理请求的功能
public static InputStream fetchInputStream(String strURL, boolean forceRefresh)
throws IOException {
HttpURLConnection mHttpConn = null;
InputStream inputStream = null;
URL url = new URL(strURL);
HttpResponseCache cache;
try {
mHttpConn = (HttpURLConnection) url.openConnection();
if (forceRefresh) {
mHttpConn.addRequestProperty("Cache-Control", "no-cache");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
cache = HttpResponseCache.getInstalled();
if (cache != null) {
Log.i("TEST CACHE", "TEST PETICION: Req count: "
+ cache.getRequestCount() + ", hit count "
+ cache.getHitCount() + ", netWork count "
+ cache.getNetworkCount() + " size = "
+ cache.size() + " <-----------------");
}
}
mHttpConn.setUseCaches(true);
mHttpConn.setDefaultUseCaches(true);
mHttpConn.setRequestMethod("GET");
mHttpConn.setConnectTimeout(30000);
mHttpConn.setReadTimeout(30000);
mHttpConn.connect();
if (mHttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = mHttpConn.getInputStream();
}
} catch (IOException ex) {
Log.e("NetworkConnectionManager InputStream", "Exception opening ["
+ strURL + "] ->", ex);
mHttpConn.disconnect();
throw ex;
}
return inputStream;
}
每次请求后
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
HttpResponseCache cache = HttpResponseCache.getInstalled();
if (cache != null) {
cache.flush();
}
}
示例请求标头:
- 缓存控制 → max-age=300
- 连接→保持活动
- 内容编码 → gzip
- 内容类型 → 应用程序/json;字符集=utf-8
- 日期 → 2015 年 4 月 8 日星期三 12:37:35 GMT
- 过期 → 格林威治标准时间 2015 年 4 月 8 日星期三 12:42:35
- 最后修改时间 → 格林威治标准时间 2015 年 4 月 8 日星期三 12:37:35
- 服务器 → nginx
- 传输编码 → 分块
- 变化 → 接受编码
- X-Cached → MISS