gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:17:45 25 4
gpt4 key购买 nike

在我的应用程序 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com