我正在使用 HttpResponseCache在我的 Android 应用程序中启用响应缓存(用于 Web 请求),并且离线缓存不工作。 我正在做离线缓存作为 documentation告诉我去做。
在我的应用程序类中,在 onCreate
方法中,我打开缓存:
try {
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
File httpCacheDir = new File(getCacheDir(), "http");
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
} catch (Exception httpResponseCacheNotAvailable) {}
在我的 HttpConnection
类中,我使用以下方法获取 JSON:
private String sendHttpGet(boolean cacheOnly) throws Exception {
URL url = new URL(getUrlCompleta());
HttpURLConnection urlConnection = null;
String retorno = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection == null)
throw new Exception("Conn obj is null");
fillHeaders(urlConnection, cacheOnly);
InputStream in = new BufferedInputStream(urlConnection.getInputStream(), 8192);
retorno = convertStream(in);
in.close();
urlConnection.disconnect();
if(retorno != null)
return retorno;
} catch(IOException e) {
throw e;
} finally {
if(urlConnection != null)
urlConnection.disconnect();
}
throw new Exception();
}
其中 convertStream
方法只是将 InputStream
解析为 String
。
fillHeaders
方法在请求上放置一个 token (出于安全原因),如果参数 cacheOnly 为 true
,则 header "Cache-Control", "only -if-cached"
添加到请求 header 中(代码为:connection.addRequestProperty("Cache-Control", "only-if-cached");
)
当存在连接且应用程序访问网络服务器只是为了查看是否有更新版本的 JSON 时,缓存工作“正常”(有轻微的奇怪行为)。当网络服务器回答“没有改变”时,缓存工作。
问题是当我没有连接并使用 header "Cache-Control", "only-if-cached"
时。在这种情况下,我收到一个 java.io.FileNotFoundException: https://api.example.com/movies.json
。这很尴尬,因为 implementation code缓存的一部分可能将响应存储在一个使用请求 url 上的哈希函数命名的文件中,而不是 url 本身。
有谁知道我能做什么或我的实现有什么问题吗?
ps: 上面,我说“可能使用哈希函数”,因为我没能找到 com.android.okhttp.HttpResponseCache 对象的实现(android.net.http.HttpResponseCache 的类)
委托(delegate)缓存调用)。如果有人找到它,请告诉我在哪里可以看到:)
ps2:即使我在 Cache-Control
header 中添加了一个 max-stale
参数,它仍然不起作用。
ps3:我显然是在 api 14+ 上测试过的。
ps4:虽然我访问的是“https://”URL 地址,但当 URL 只是一个普通的“http://”地址时,同样的行为也会发生。
最佳答案
事实证明,问题出在我的 Web 服务器给出的响应中 Cache-control
指令的 max-age
值。它具有以下值:Cache-Control: max-age=0, private, must-revalidate
。使用此指令,我的服务器对缓存说响应可以从缓存中使用,即使它是 0 秒旧的。所以,我的连接没有使用任何缓存的响应。
知道 max-age 是以秒为单位指定的,我所要做的就是将值更改为:Cache-Control: max-age=600, private, must-revalidate
!好了,现在我有 10 分钟的缓存。
编辑:如果你想使用过时的响应,通过请求的 max-stale
指令,你不应该在请求中使用 must-revalidate
指令响应,就像我在网络服务器中所做的那样。
关于android - 使用 HttpResponsecache 的离线缓存时出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788568/