Android 使用HttpResponsecache的脱机缓存时FileNotFoundException

Android 使用HttpResponsecache的脱机缓存时FileNotFoundException,android,caching,Android,Caching,我正在使用启用android应用程序中的响应缓存(用于web请求),但脱机缓存不起作用。 我正在按命令进行脱机缓存 在我的应用程序类中,在onCreate方法中,我使用以下命令打开缓存: try { long httpCacheSize = 10 * 1024 * 1024; // 10 MiB File httpCacheDir = new File(getCacheDir(), "http"); Class.forName("android.net.http.Http

我正在使用启用android应用程序中的响应缓存(用于web请求),但脱机缓存不起作用。 我正在按命令进行脱机缓存

在我的应用程序类中,在
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
解析为
字符串
。 方法
fillHeaders
在请求上放置一个令牌(出于安全原因),如果参数cacheOnly为
true
,则将头
“缓存控制”,“仅当缓存时”
添加到请求头(代码为:
connection.addRequestProperty(“缓存控制”,“仅当缓存时”);

当存在连接时,缓存工作“正常”(有轻微的奇怪行为),应用程序点击web服务器只是为了查看是否有更新版本的JSON。当web服务器回答“未更改”时,缓存工作

问题是当我没有连接并且使用标题
“缓存控制”,“仅当缓存时”
。在本例中,我收到一个
java.io.FileNotFoundException:https://api.example.com/movies.json
。这很尴尬,因为缓存的名称可能将响应存储在一个名为的文件中,该文件在请求url上使用哈希函数,而不是url本身

有人知道我能做什么,或者我的实现有什么问题吗

ps:上面,我说“可能使用散列函数”,因为我找不到com.android.okhttp.HttpResponseCache对象(代理缓存调用的
android.net.http.HttpResponseCache
类)的实现。如果有人发现了,请告诉我在哪里看:)

ps2:即使我在
缓存控制
头中添加
max stale
参数,它仍然不起作用

ps3:我显然是在api 14+上测试的


ps4:虽然我正在访问一个“https://”URL地址,但当URL只是一个正常的“http://”地址时,同样的行为也会发生。

事实证明,问题出在我的web服务器给出的响应中
缓存控制
指令的
max age
值上。它具有以下值:
缓存控制:max age=0,private,必须重新验证。有了这个指令,我的服务器对缓存说,即使响应已经0秒了,也可以从缓存中使用响应。因此,我的连接没有使用任何缓存响应

知道max age是以秒为单位指定的,我所要做的就是将该值更改为:
缓存控制:max age=600,private,必须重新验证
!好了,现在我有一个10分钟的缓存

编辑:如果您想使用过时响应,那么在请求的
max stale
指令中,您不应该在响应中使用
must revalidate
指令,就像我在Web服务器中所做的那样