OKHttp cache with expiration

佐手、 提交于 2019-12-14 03:07:23

问题


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.


回答1:


You can use MaxAge and MaxStale parameter of 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();
        }
    };
}

And later you can add this to your HttpClient

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


来源:https://stackoverflow.com/questions/47869318/okhttp-cache-with-expiration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!