0
votes

I'm trying to cache response via OkHttp and Retrofit. I understand there are several questions similar to mine but none of those are able to address my issue.

Following is my Interceptor responsible for modifying the headers.

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

            Response originalResponse = chain.proceed(request);
            return originalResponse.newBuilder()
                    .header("Cache-Control", (UtilityMethods.isNetworkAvailable()) ?
                            "public, max-age=60" :  "public, max-stale=604800")
                    .build();
        }
    }

Now, this works perfectly in the first case -

  1. Internet connection is available.
  2. A valid response is received and cached.
  3. Disconnect the device from the internet.
  4. Send the same request as previous one within a minute -> Response is same as last
  5. Next, send the same request after a minute is complete -> No response (UnknownHostException)

This makes the first part ("public, max-age=60") complete.

But, somehow, "public, max-age=60" part does not work at all.

This part should enable okhttp to fetch the a week old stale data when the device is offline but instead, I get UnknownHostException.

1

1 Answers

2
votes

I think this is what you are looking for :

.header("Cache-Control", (UtilityMethods.isNetworkAvailable()) ?
            "public, max-age=60" :  "public, only-if-cached, max-stale=604800")

This adds the only-if-cached directive for when the network is unavailable. This only accepts the response if it is in the cache.