Android HttpResponseCache 不工作 - FileNotFoundException
Posted
技术标签:
【中文标题】Android HttpResponseCache 不工作 - FileNotFoundException【英文标题】:Android HttpResponseCache not working - FileNotFoundException 【发布时间】:2014-12-16 08:48:41 【问题描述】:我在 android 中缓存来自 Web 服务器的 http(s) 响应时遇到问题,文档很差,所以我在这里寻求帮助。这是我的代码:
String encodedString = String.format("jsonData=%s", URLEncoder.encode(json, "UTF-8"));
URL urlConn = new URL(url+"?"+encodedString);
HttpURLConnection cachedUrlConnection = (HttpURLConnection) urlConn.openConnection();
cachedUrlConnection.setUseCaches(true);
cachedUrlConnection.setDoInput(true);
cachedUrlConnection.setDoOutput(true);
cachedUrlConnection.setRequestProperty("charset", "utf-8");
cachedUrlConnection.setRequestMethod("GET");
cachedUrlConnection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream is = null;
try
is = cachedUrlConnection.getInputStream();
Log.i("_INFO","------CACHE FOUNDED");
catch (FileNotFoundException e)
e.printStackTrace();
HttpURLConnection nonCachedUrlConnection = (HttpURLConnection) urlConn.openConnection();
nonCachedUrlConnection.setUseCaches(true);
nonCachedUrlConnection.setDoInput(true);
nonCachedUrlConnection.setDoOutput(true);
nonCachedUrlConnection.setRequestProperty("charset", "utf-8");
nonCachedUrlConnection.setRequestMethod("GET");
nonCachedUrlConnection.addRequestProperty("Cache-Control", "max-stale=" + (60 * 60 * 24));
Log.i("_INFO","-------CACHE NOT FOUNDED");
is = nonCachedUrlConnection.getInputStream();
另外,我已经在 Application onCreate 方法上安装了缓存,如下所示:
try
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
File httpCacheDir = new File(getExternalCacheDir(), "http");
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
Log.i("_INFO", "HttpResponseCache enabled");
catch (Exception httpResponseCacheNotAvailable)
Log.d("_INFO", "HTTP response cache is unavailable.");
并且如果我打印缓存大小,在应用程序重新启动后,它会正确打印 2 mb 的缓存大小(因此它会正确缓存)。我在所有 HTTP 调用之后刷新缓存,如下所示:
HttpResponseCache cache = HttpResponseCache.getInstalled();
if(cache != null)
Log.i("_INFO", "CACHED FLUSHED WITH " + cache.size());
cache.flush();
所以,基本上,缓存过程工作得很好,但是当我获取输入流时,我无法获取缓存的响应。我的 logcat 总是打印“CACHE NOT FOUNDED”。
【问题讨论】:
第二个'.getInputStream()'的结果是什么? @greenapps 它是一个正确的 InputStream,由正常的下载请求处理。基本上永远不会到达第一个“缓存”输入流。long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
和 it prints correctly a cache size of 2 mb
???你的意思是2MB?但为什么不是 10MB?
So, basically, the cache process works great,
。您是否检查了是否创建了 http 目录?你检查过它是否有内容吗?
但我想知道:这种缓存的目的是什么?有什么用?
【参考方案1】:
一段时间后,我得到了解决方案,似乎我的 HTTP 调用中的参数太多,或者可能是错误的。
只有:
cachedUrlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
这个,缓存很迷人。
【讨论】:
以上是关于Android HttpResponseCache 不工作 - FileNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章
Android HttpResponseCache 不工作 - FileNotFoundException
java.lang.NoClassDefFoundError 与 HttpResponseCache 和 DiskLruCache