【问题标题】:OKHttp cache with expirationOKHttp缓存过期
【发布时间】:2018-05-31 20:18:50
【问题描述】:

我是 OkHttpClient 的新手,我不知道如何只存储 1 周的缓存。
所以当代理更新数据时,它也会在 1 周后在移动端更新。

【问题讨论】:

    标签: android caching okhttp3


    【解决方案1】:

    可以使用CacheControl MaxAgeMaxStale参数

    MaxAge

    设置缓存响应的最长期限。如果缓存响应的年龄超过MaxAge,它将不会被使用并会发出网络请求

    MaxStale

    接受已超过其新鲜寿命最多MaxStale 的缓存响应。如果未指定,则不会使用过时的缓存响应

    public Interceptor provideCacheInterceptor(final int maxDays) {      
        return new Interceptor() {       
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                CacheControl cacheControl = new CacheControl.Builder()
                    .maxAge(maxDays, TimeUnit.DAYS)
                    .build();
        
                return response.newBuilder()
                    .header(Constants.CACHE_CONTROL, cacheControl.toString())
                    .build();
            }
        };
    }
    

    稍后您可以将其添加到您的HttpClient

    int MaxCacheDays = 7; 
    httpClient.addNetworkInterceptor(provideCacheInterceptor(MaxCacheDays));
    

    【讨论】:

    • 感谢您的精彩回答
    • 如果这回答了您的问题,那么您可以接受它。谢谢
    猜你喜欢
    • 2019-08-09
    • 2017-08-05
    • 2017-05-07
    • 2016-08-03
    • 1970-01-01
    • 2016-08-19
    • 2015-01-01
    • 2018-06-19
    • 2017-02-03
    相关资源
    最近更新 更多