我最近将我的应用程序从使用 AndroidHTTPClient 切换到使用 HttpURLConnection。我正在尝试使 HttpURLConnection 的缓存功能起作用,但没有成功。
这是我执行 Http 请求的代码
URL url = new URL(currentURL);
ResultAndUrl result = null;
final HttpURLConnection httpUrlConnection = (HttpURLConnection) urll.openConnection();
httpUrlConnection.setUseCaches(true);
try {
InputStream in = new BufferedInputStream(httpUrlConnection.getInputStream());
result = new ResultAndUrl();
result.result = convertStreamToString(in);
result.url = currentURL;
} catch (final Exception e) {
try {
Log.e("NETWORK", e.getMessage());
} catch (Exception ee) {
}
} finally {
try {
httpUrlConnection.disconnect();
} catch (Exception e) {
}
}
同样在我的应用程序类中,我有
public void enableHttpResponseCache() {
final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
final File httpCacheDir = new File(getCacheDir(), "http");
try {
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
} catch (Exception httpResponseCacheNotAvailable) {
try{
HttpResponseCache.install(httpCacheDir, httpCacheSize); // Library that implements HttpResponseCache for pre-ICS phones
} catch(Exception e){
}
}
}
然而,即使对于 ICS 手机,也没有发生过缓存命中,而且缓存似乎根本没有做任何事情。你能告诉我我做错了什么,或者错过了什么吗?