Retrofit offline request and response

前端 未结 1 844
别跟我提以往
别跟我提以往 2021-01-21 12:20

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.

相关标签:
1条回答
  • 2021-01-21 12:48

    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:

    Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (!isOnline()) {
                        int maxStale = 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);
                }
            };
    
    
    Interceptor ONLINE_INTERCEPTOR = new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    okhttp3.Response response = chain.proceed(chain.request());
                     int maxAge = 60; // read from cache
                    return response.newBuilder()
                             .header("Cache-Control", "public, max-age=" + maxAge)
                            .build();
                }
            };
    

    2)Add Interceptors to okHttpClient

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                //.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .addInterceptor(OFFLINE_INTERCEPTOR)
                .addNetworkInterceptor(ONLINE_INTERCEPTOR)
                .cache(provideOkHttpCache())
                .build();
    

    Link to original article

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