Skip to content Skip to sidebar Skip to footer

Okhttp 3 Response Cache (java.net.unknownhostexception)

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. Also I set Cache-Contlo

Solution 1:

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 :

InterceptorcacheInterceptor=newInterceptor() {
            @Overridepublic okhttp3.Response intercept(Chain chain)throws IOException {

                CacheControl.BuildercacheBuilder=newCacheControl.Builder();
                cacheBuilder.maxAge(0, TimeUnit.SECONDS);
                cacheBuilder.maxStale(365,TimeUnit.DAYS);
                CacheControlcacheControl= cacheBuilder.build();

                Requestrequest= chain.request();
                if(isOnline()){
                    request = request.newBuilder()
                            .cacheControl(cacheControl)
                            .build();
                }
                okhttp3.ResponseoriginalResponse= chain.proceed(request);
                if (isOnline()) {
                    intmaxAge=60; // read from cachereturn originalResponse.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .build();
                } else {
                    intmaxStale=60 * 60 * 24 * 28; // tolerate 4-weeks stalereturn 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):

OkHttpClientokHttpClient=newOkHttpClient.Builder()
        .addInterceptor(httpLoggingInterceptor)
        .addNetworkInterceptor(cacheInterceptor)
        .cache(provideOkHttpCache())
        .build();

The original answer:Caching with Retrofit 2.0 and okhttp3

Post a Comment for "Okhttp 3 Response Cache (java.net.unknownhostexception)"