Skip to content

Retrofit + OkHTTP - response cache not working #5

@CHRehan

Description

@CHRehan

This implementation worked correctly to cache file to get from S3 using picasso and okhttp but it will not worked in case of POST request..

         private Interceptor provideCacheInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            // re-write response header to force use of cache
            CacheControl cacheControl = new CacheControl.Builder().maxAge(2, TimeUnit.MINUTES).build();

            return response.newBuilder().header(CACHE_CONTROL, cacheControl.toString()).build();
        }
    };
}

private Interceptor provideOfflineCacheInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (!MyApplication.hasNetwork()) {
                CacheControl cacheControl = new CacheControl.Builder().maxStale(7, TimeUnit.DAYS).build();

                request = request.newBuilder().cacheControl(cacheControl).build();
            }

            return chain.proceed(request);
        }
    };

Here is the code of my OkHttpClient

@Provides public OkHttpClient okHttpClient(Cache cache, HttpLoggingInterceptor httpLoggingInterceptor, CustomInterceptors customInterceptors) { return new OkHttpClient().newBuilder().readTimeout(50, TimeUnit.SECONDS).writeTimeout(55, TimeUnit.SECONDS).connectTimeout(50, TimeUnit.SECONDS).cache(cache).addInterceptor(httpLoggingInterceptor) .addInterceptor(provideOfflineCacheInterceptor()).addNetworkInterceptor(provideCacheInterceptor()).build(); }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions