OkHttp 3 response cache (java.net.UnknownHostException)

可紊 提交于 2019-12-02 10:44:57

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!