我一直在我的应用中成功使用HttpResponseCache,但当我的手机更新到Lollipop后,我意识到HttpResponseCache现在永远不会被“命中”,总是进行网络请求。我已经确认在Android Lollipop之前的版本中仍然工作正常。 也许是我做错了什么,在新的Android更改中出现了问题。
有人有任何想法吗?
我的代码:
Application类,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();
}
}
示例请求头:
- Cache-Control → max-age=300
- 连接 → keep-alive
- 内容编码 → gzip
- 内容类型 → application/json; charset=utf-8
- 日期 → Wed, 08 Apr 2015 12:37:35 GMT
- 过期时间 → Wed, 08 Apr 2015 12:42:35 GMT
- 最后修改时间 → Wed, 08 Apr 2015 12:37:35 GMT
- 服务器 → nginx
- 传输编码方式 → chunked
- 变化 → Accept-Encoding
- X-Cached → MISS