OKHttp缓存有效期

问题描述 投票:0回答:1

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

android caching okhttp3
1个回答
0
投票

你可以使用MaxAgeMaxStaleCacheControl参数

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));
© www.soinside.com 2019 - 2024. All rights reserved.