问题
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