Okhttp Cache With Expiration
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.
Solution 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(finalint maxDays) {
returnnewInterceptor() {
@Overridepublic Response intercept(Chain chain)throws IOException {
Responseresponse= chain.proceed(chain.request());
CacheControlcacheControl=newCacheControl.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));
Post a Comment for "Okhttp Cache With Expiration"