android - 使用 OkHttp 进行缓存(无需改造)

标签 android okhttp

在我的应用程序 onCreate 中,我正在创建一个 10MB 的缓存:

try
{
    File httpCacheDir = new File(getApplicationContext().getCacheDir(), Constants.AppName);
    long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
    HttpResponseCache.install(httpCacheDir, httpCacheSize);
}
catch (IOException ex)
{
    Log.i(Constants.AppName, "HTTP response cache installation failed: " + ex);
}

我对资源的调用:

OkHttpClient client = new OkHttpClient();
client.setResponseCache(HttpResponseCache.getInstalled());

HttpURLConnection connection = client.open(url);
connection.addRequestProperty("Cache-Control", "max-age=60");
InputStream inputStream = connection.getInputStream();

我将在 10 秒内初始化此调用两次,OkHttp-Response-Source header 始终为 NETWORK 200。

for (Map.Entry<String, List<String>> k : connection.getHeaderFields().entrySet())
{
    for (String v : k.getValue())
    {
        Log.d(Constants.AppName, k.getKey() + ": " + v);
    }
}

我在这里错过了什么?

最佳答案

OkHttp 实现HTTP 1.1 RFC for HTTP cache .这意味着,对于您尝试访问的任何 URL,响应至少需要返回 Cache-Control header :

The basic cache mechanisms in HTTP/1.1 (server-specified expiration times and validators) are implicit directives to caches. In some cases, a server or client might need to provide explicit directives to the HTTP caches. We use the Cache-Control header for this purpose.

The Cache-Control header allows a client or server to transmit a variety of directives in either requests or responses. These directives typically override the default caching algorithms. As a general rule, if there is any apparent conflict between header values, the most restrictive interpretation is applied (that is, the one that is most likely to preserve semantic transparency). However,

in some cases, cache-control directives are explicitly specified as weakening the approximation of semantic transparency (for example, "max-stale" or "public").

The cache-control directives are described in detail in section 14.9.

关于android - 使用 OkHttp 进行缓存(无需改造),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735068/

相关文章:

android - 在 Retrofit 2 和 OkHttp3 中使用 @PUT

java - 使用 Retrofit 2 进行日志记录

android - 更改 Leanback 库中 DetailsFragment 中 Action 按钮的默认选择颜色

java - 从数组中添加多个标记

android - Okhttp - OkHttpClient 2.0.0 无法解析方法拦截器()

java - 如何控制 okHttpClient 的连接大小?

android - 无法在 OkHttp3 : Level has private access and SetLevel is deprecated 中设置级别

java - 有多个好的构造函数,Room 会选择无参数构造函数

android - 我可以在 NDK 应用程序中使用 native 库(安装在 Android 堆栈中)吗?

java - Android Firebase 数据库路径无效