【发布时间】:2018-05-31 20:18:50
【问题描述】:
我是 OkHttpClient 的新手,我不知道如何只存储 1 周的缓存。
所以当代理更新数据时,它也会在 1 周后在移动端更新。
【问题讨论】:
我是 OkHttpClient 的新手,我不知道如何只存储 1 周的缓存。
所以当代理更新数据时,它也会在 1 周后在移动端更新。
【问题讨论】:
可以使用CacheControl 的MaxAge和MaxStale参数
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));
【讨论】: