Retrofit Offline Request And Response
I've already read many questions and answers about my issue, but I slill can't understand how to solve it. I need to fetch response from server and store it in cache. After that wh
Solution 1:
Solved.
The trick is in combining Interceptor
and NetworkInterceptor
.
Steps:
1)Separate REWRITE_CACHE_CONTROL_INTERCEPTOR for two Interceptors, one for online work and other for offline work:
InterceptorOFFLINE_INTERCEPTOR=newInterceptor() {
@Overridepublic okhttp3.Response intercept(Chain chain)throws IOException {
Requestrequest= chain.request();
if (!isOnline()) {
intmaxStale=60 * 60 * 24 * 28; // tolerate 4-weeks stale
request = request.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return chain.proceed(request);
}
};
InterceptorONLINE_INTERCEPTOR=newInterceptor() {
@Overridepublic okhttp3.Response intercept(Chain chain)throws IOException {
okhttp3.Responseresponse= chain.proceed(chain.request());
intmaxAge=60; // read from cachereturn response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
}
};
2)Add Interceptors to okHttpClient
OkHttpClientokHttpClient=newOkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(OFFLINE_INTERCEPTOR)
.addNetworkInterceptor(ONLINE_INTERCEPTOR)
.cache(provideOkHttpCache())
.build();
Post a Comment for "Retrofit Offline Request And Response"