OkHttp 3 response cache (java.net.UnknownHostException)

后端 未结 1 738
轮回少年
轮回少年 2021-01-28 04:59

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

1条回答
  •  旧时难觅i
    2021-01-28 05:30

    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

    0 讨论(0)
提交回复
热议问题