缓存与OkHttp(不含改装) [英] Caching with OkHttp (without Retrofit)

查看:212
本文介绍了缓存与OkHttp(不含改装)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Application onCreate, I'm creating a 10MB cache:

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 - 响应源的头始终是网络200。

I'll initialize this call twice, within 10 seconds of one another, and the OkHttp-Response-Source header is always NETWORK 200.

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

我是什么在这里失踪?

What am I missing here?

推荐答案

OkHttp实施的 HTTP 1.1 RFC的HTTP缓存。这意味着,你正在试图达成任何URL,响应需要返回至少的Cache-Control 标题:

OkHttp implement the HTTP 1.1 RFC for HTTP cache. That means, for any URL your are trying to reach, the response needs to return at least the Cache-Control header:

在HTTP的基本缓存机制/ 1.1(服务器指定的过期
  时间和验证器)是隐性的指令来缓存。在一些
  情况下,服务器或客户端可能需要提供明确的指示,以
  在HTTP缓存。我们使用Cache-Control头用于这一目的。

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.

在Cache-Control头允许客户端或服务器发送一个
  各种要么请求或响应指令。这些
  通常指令覆盖缺省的缓存算法。作为一个
  一般情况下,如果有标题值之间的任何明显的冲突,
  最严格的跨pretation应用(也就是一个
  最有可能preserve语义透明)。不过,

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,

在某些情况下,高速缓存控制指令被明确地指定为
  削弱语义透明的近似(例如,
  MAX-陈旧或公开)。

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

缓存控制指令的部分中,详细描述了14.9

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

这篇关于缓存与OkHttp(不含改装)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆