HTTP Caching with Retrofit 2.0.x

纵然是瞬间 提交于 2019-12-02 18:18:29
Amr Barakat

Finally I get the answer.

Network Interceptor should be as follow:

public class CachingControlInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // Add Cache Control only for GET methods
        if (request.method().equals("GET")) {
            if (ConnectivityUtil.checkConnectivity(YaootaApplication.getContext())) {
                // 1 day
               request = request.newBuilder()
                        .header("Cache-Control", "only-if-cached")
                        .build();
            } else {
                // 4 weeks stale
               request = request.newBuilder()
                        .header("Cache-Control", "public, max-stale=2419200")
                        .build();
            }
        }

        Response originalResponse = chain.proceed(request);
        return originalResponse.newBuilder()
            .header("Cache-Control", "max-age=600")
            .build();
    }
}

then installing cache file is that simple

long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(new File(context.getCacheDir(), "http"), SIZE_OF_CACHE);
OkHttpClient client = new OkHttpClient();
client.cache(cache);
client.networkInterceptors().add(new CachingControlInterceptor());

In your CachingControlInterceptor, you create new requests, but never actually use them. You call newBuilder and ignore the result, so the header modification is never actually sent any where. Try assigning those values to request and then instead of calling proceed on chain.request() call it on request.

public class CachingControlInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // Add Cache Control only for GET methods
        if (request.method().equals("GET")) {
            if (ConnectivityUtil.checkConnectivity(getContext())) {
                // 1 day
                request = request.newBuilder()
                    .header("Cache-Control", "only-if-cached")
                    .build();
            } else {
                // 4 weeks stale
                request = request.newBuilder()
                    .header("Cache-Control", "public, max-stale=2419200")
                    .build();
            }
        }

        Response originalResponse = chain.proceed(request);
        return originalResponse.newBuilder()
            .header("Cache-Control", "max-age=600")
            .build();
    }
}

you can also try:

public class CachingInterceptor implements Interceptor {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        request = new Request.Builder()
                .cacheControl(new CacheControl.Builder()
                        .maxAge(1, TimeUnit.DAYS)
                        .minFresh(4, TimeUnit.HOURS)
                        .maxStale(8, TimeUnit.HOURS)
                        .build())
                .url(request.url())
                .build();


        return chain.proceed(request);
    }
}

I finally discovered the solution that worked for me in Retrofit 2.x and OkHttp 3.x

I had to implement two Interceptors, one of them is responsible to rewrite the Request headers and the other to rewrite the Response headers.

  1. First, make sure you delete any old cache. (root explorer /data/data/com.yourapp/cache

  2. Instantiate the client builder:

    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
        .cache(cache)
        .addInterceptor(new RewriteRequestInterceptor())
        .addNetworkInterceptor(new RewriteResponseCacheControlInterceptor())
    
  3. Create the RewriteRequestInterceptor

    public class RewriteRequestInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            int maxStale = 60 * 60 * 24 * 5;
            Request request;
            if (NetworkUtils.isNetworkAvailable()) {
                request = chain.request();
            } else {
                request = chain.request().newBuilder().header("Cache-Control", "max-stale=" + maxStale).build();
            }
            return chain.proceed(request);
        }
    }
    
  4. Create the RewriteResponseCacheControlInterceptor

    public class RewriteResponseCacheControlInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            int maxStale = 60 * 60 * 24 * 5;
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().header("Cache-Control", "public, max-age=120, max-stale=" + maxStale).build();
        }
    }
    

It's important to make sure you add the ResponseCacheControlInterceptor as a Network Interceptor, and the RewriteRequestInterceptor as a Interceptor (as I did in the 2nd step).

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