【问题标题】:How to change default cache policy in Okhttp?如何更改 Okhttp 中的默认缓存策略?
【发布时间】:2023-04-06 22:19:04
【问题描述】:

我正在使用 Picasso 进行图像加载。毕加索没有磁盘缓存。 OkHttp 维护一个由 HTTP 缓存头控制的 HTTP 缓存。我想为磁盘缓存图像设置过期时间,因此在 HTTP 响应 cache-control: public, max-age=7200 中添加了缓存控制标头,但它不尊重缓存标头。当前行为是遵循 RFC 7234 的默认 HTTPResponseCache。 我们有什么遗漏吗?

【问题讨论】:

    标签: android http picasso okhttp


    【解决方案1】:

    您可以使用网络拦截器重写响应中的缓存标头。以下是来自OkHttp interceptors doc 的示例,可帮助您入门:

    /** Dangerous interceptor that rewrites the server's cache-control header. */
    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
      @Override public Response intercept(Interceptor.Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
            .header("Cache-Control", "max-age=60")
            .build();
      }
    };
    

    请注意,您可能需要从服务器响应中删除标头以获得所需的缓存行为。

    另请注意,最好修复服务器以执行您想要的操作;这样它就可以在 iOS 和网络上正常工作。

    【讨论】:

    • 我们尝试从客户端设置标头,但仍然不尊重 Cache-Control 标头。有什么方法可以告诉 okhttp 缓存这么多小时?
    猜你喜欢
    • 2016-10-15
    • 2010-12-02
    • 2019-09-19
    • 2012-03-28
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2021-06-22
    相关资源
    最近更新 更多