我正在使用DefaultHTTPClient
来进行一些HTTP GET请求。我想强制缓存一周的所有HTTP响应。通过文档和一些SO回答后,我已经这样做了:如何强制缓存我所有的HTTP响应?
我通过我主要活动的onCreate
方法安装了HttpResponseCache
。
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) {
Log.i("dd", "HTTP response cache installation failed:" + e);
}
我加了一个自定义的HttpResponseInterceptor
我的HTTP客户端,但我仍然没有得到缓存命中。下面是解压gzip压缩的内容我的反应拦截,剥离缓存头,并增加了一个自定义的:
class Decompressor implements HttpResponseInterceptor {
public void process(HttpResponse hreResponse, HttpContext hctContext) throws HttpException, IOException {
hreResponse.removeHeaders("Expires");
hreResponse.removeHeaders("Pragma");
hreResponse.removeHeaders("Cache-Control");
hreResponse.addHeader("Cache-Control", "max-age=604800");
HttpEntity entity = hreResponse.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
hreResponse.setEntity(new HttpEntityWrapper(entity) {
@Override
public InputStream getContent() throws IOException, IllegalStateException {
return new GZIPInputStream(wrappedEntity.getContent());
}
@Override
public long getContentLength() {
return -1;
}
});
return;
}
}
}
}
}
}
下面是如何使我的要求:
String strResponse = null;
HttpGet htpGet = new HttpGet(strUrl);
htpGet.addHeader("Accept-Encoding", "gzip");
htpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
DefaultHttpClient dhcClient = new DefaultHttpClient();
dhcClient.addResponseInterceptor(new Decompressor(), 0);
HttpResponse resResponse = dhcClient.execute(htpGet);
Log.d("helpers.network", String.format("Cache hit count: %d", HttpResponseCache.getInstalled().getHitCount()));
strResponse = EntityUtils.toString(resResponse.getEntity());
return strResponse;
我似乎无法找出什么我做错了。你们中的任何人都知道吗?
Idk什么'HttpResonseCache'可以做,但你可以创建一个文件缓存封装HttpClient手动或者你可以尝试使用'HttpUrlConnection'它有缓存,因为ICS http://android-developers.blogspot.de/2011/09/androids -http-clients.html – zapl
有一个叫做缓存控制的标题信息,我不确定它可以帮忙或没有帮助,但是如果你仍然想知道该怎么做,请对此进行一些研究。 –
@Dhruvenkumar Shah,如果你看看我的代码,你会看到我手动设置'Cache-Control'头。 –