How to update OkHttp cache

808 Views Asked by At

In my android application I am caching responses from the server using OkHttp. for that I have implemented code as follows

     private class CacheInterceptor implements Interceptor {

        Context mContext;

        public CacheInterceptor(Context context) {
            this.mContext = context;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
                request = request.newBuilder()
                        .header(HEADER_MOBILE_OS, Constants.MOBILE_OS)
                        .header(HEADER_APP_VERSION, BuildConfig.VERSION_NAME)
                        .build();
            Response response = chain.proceed(request);

            if (!mShouldUpdateCache) {
                response.newBuilder()
                        .header("Cache-Control", String.format("max-age=%d", CACHE_MAX_AGE)).build();
            } else {
//update cache in this case
                response.newBuilder()
                        .header("Cache-Control", "no-cache").build();
                mShouldUpdateCache = false;
            }
            return response;
        }
    }

this is my interceptor class and I am setting this to OkClient as follows

okHttpClient.networkInterceptors().add(new CacheInterceptor(context));

    File httpCacheDirectory = new File(context.getCacheDir(), "response_cache");
    Cache cache = new Cache(httpCacheDirectory, CACHE_SIZE);

    if (cache != null) {
        okHttpClient.setCache(cache);
    }

but the problem is, when the boolean mShouldUpdateCache becomes true I have to update the cache. right now I have wrote response.newBuilder().header("Cache-Control", "no-cache").build(); but it is neither updating the cache nor fetching from server , how do I resolve this issue ?

1

There are 1 best solutions below

6
On

I suspect your network interceptor doesn't execute for responses served from the cache, because the network is not used for those requests. From the interceptors doc, network interceptors are “Not invoked for cached responses that short-circuit the network.”

Hacking the response headers on the client is a fragile way to do HTTP caching. You should use appropriate request headers and get your webserver go set appropriate response headers.