Caching with Retrofit 2.0 and okhttp3

左心房为你撑大大i 提交于 2019-12-04 19:39:54

I have meet the same problem with u , now i find a article and solve my problem , i think it's can help u.

Because out of the time of get cache , okhttp will empty cache and request server again , now cache was empty , so it will send error Exception.

We can set some request setting with you'r Interceptor.

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(!StateUtils.isNetworkAvailable(MyApp.mContext)){
                request = request.newBuilder()
                        .cacheControl(cacheControl)
                        .build();
            }

maxAge : Controll the cache lifetime maximum

maxStale : Controll the cache Out of date time

Full code :

weiBoApiRetrofit() {

        File httpCacheDirectory = new File(MyApp.mContext.getCacheDir(), "responses");
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(httpCacheDirectory, cacheSize);

        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        WeiBoApiService = retrofit.create(WeiBoApi.class);
    }

    //cache
    Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public 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(StateUtils.isNetworkAvailable(MyApp.mContext)){
                request = request.newBuilder()
                        .cacheControl(cacheControl)
                        .build();
            }
            Response originalResponse = chain.proceed(request);
            if (StateUtils.isNetworkAvailable(MyApp.mContext)) {
                int maxAge = 60  * 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();
            }
        }
    };
}

i can solve my problem.

but i didn't know why setting header in Response of Interceptor Useless , some people say " Interceptor must setting set those two request and Response "

I hope I can help you .

alexey polusov

Setting header this way (exactly 50000) solved the issue.

.header("Cache-Control", String.format("max-age=%d", 50000))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!