I\'m really stuck at this problem.
I want to cache server response for some time to use the data when device is offline.
So I set a cache to my OkHttpClient
Well, I found the solution. I'm not sure why does it work, but it really does.
First we need to modify creation of cacheInterceptor
:
Interceptor cacheInterceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
CacheControl.Builder cacheBuilder = new CacheControl.Builder();
cacheBuilder.maxAge(0, TimeUnit.SECONDS);
cacheBuilder.maxStale(365,TimeUnit.DAYS);
CacheControl cacheControl = cacheBuilder.build();
Request request = chain.request();
if(isOnline()){
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}
okhttp3.Response originalResponse = chain.proceed(request);
if (isOnline()) {
int maxAge = 60; // read from cache
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
}
};
Then we need to use addNetworkInterceptor(Interceptor interceptor)
instead addInterceptor(Interceptor interceptor)
:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addNetworkInterceptor(cacheInterceptor)
.cache(provideOkHttpCache())
.build();
The original answer:Caching with Retrofit 2.0 and okhttp3