我正在尝试使用HttpResponseCache但是没有运气让它运转起来。
我正在安装它:
SdCardManager manager = SdCardManager.getSdCardManager(context);
File dir = new File(manager.getAbsolutePathForSdCardFile(""), "http");
Log.e("Test", "Installing cache to " + dir.getAbsolutePath());
HttpResponseCache.install(dir, 10 * 1024 * 1024);
我的连接代码是:
try{
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) ((mProxy == null) ? url
.openConnection() : url.openConnection(mProxy.getProxy()));
HttpResponseCache cache = HttpResponseCache.getInstalled();
Log.e("Test", "Req count: " + cache.getRequestCount() + " hit count " + cache.getHitCount() + " size = " + cache.size());
connection.setUseCaches(true);
connection.setDefaultUseCaches(true);
connection.addRequestProperty("Cache-Control", "max-stale=" + (60 * 60 * 24 * 28));
applyHeaders(connection);
connection.setRequestMethod("GET");
connection.setConnectTimeout(mTimeout);
connection.setReadTimeout(mTimeout);
connection.connect();
mStatusCode = connection.getResponseCode();
mStatusMessage = connection.getResponseMessage();
connection.disconnect();
}
catch (IOException ex) {
ex.printStackTrace();
return false;
}
查看adb shell,我看到正在创建的缓存目录,它有一个日志文件。但是,不再有数据发送到目录:
shell@maguro:/storage/emulated/legacy/Android/data/com.snip.pre/files/http $ ls
journal
我在每次请求后刷新缓存:
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.flush();
任何想法我做错了什么?服务器响应标头位于:
GET /imgv.oms/0.0.1fd02.a7003c2a HTTP/1.1
Cache-Control: max-stale=2419200
Authorization: Basic bWFydGlubDppc2lz
X-Loginpageredirect: none
Accept: image/*
Accept-Encoding: gzip,deflate
Accept-Language: en-GB
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.3; Galaxy Nexus Build/JWR66Y)
Host: appsdev2.server.com:81
Connection: Keep-Alive
Cookie: POSESSIONID=F8654323-f7frSyNmAGKsvE4nFXZJQIIy3Io
是否有任何阻止它被缓存的内容?
答案 0 :(得分:1)
问题是我发送了Authorization标头,标准对这些请求是否可缓存有特定的规则。见
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html第14.8节
服务器不允许我缓存结果,因为njzk2也提到了。