OKHttp缓存到期 [英] OKHttp cache with expiration

查看:266
本文介绍了OKHttp缓存到期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OkHttpClient的新手,我不知道如何仅将缓存存储1周.
因此,当代理更新数据时,它也会在1周后在移动设备中更新.

I am new to OkHttpClient and i don't know how to store cache for only 1 week.
So when agent update data, it will update in mobile too after 1 week.

推荐答案

您可以使用CacheControl

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

Sets the maximum age of a cached response. If the cache response's age exceeds MaxAge it will not be used and a network request will be made

接受已超过其新鲜度生存期达MaxStale的缓存响应.如果未指定,将不使用过时的缓存响应

Accept cached responses that have exceeded their freshness lifetime by up to MaxStale. If unspecified, stale cache responses will not be used

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

And later you can add this to your HttpClient

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

这篇关于OKHttp缓存到期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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