1

Im using Retrofit2 & OKHTTP3 for REST API's in my android application. My requirement is I have to cache the requests to use the application in offline mode. The thing is Im able to cache the requests. But when the user goes online again , data should be fetched freshly from backend, it should not serve the cached response. How can I achieve this. Below is my network Interceptor

Network Interceptor

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


            if (Util.isOnline()) {
                request = request.newBuilder()
                        .header("Cache-Control", "only-if-cached")
                        .build();
            } else {
                request = request.newBuilder()
                        .header("Cache-Control", "public, max-stale=2419200")
                        .build();
            }

        Response response= chain.proceed(request);
        return response.newBuilder()
                .header("Cache-Control", "max-age=86400")
                .build();
    }
}
Sasank Sunkavalli
  • 3,864
  • 5
  • 31
  • 55

2 Answers2

0

Refer this answer link OkHttp Interceptor is the right way to access cache when offline:

Community
  • 1
  • 1
0

Got it . If the device is offline , I'm setting the Cache-Control header as "public, only-if-cached, max-stale=86400" (This will set the stale time to 1 day). Now if the device is online it will freshly fetch from server.

OkHttpClient

okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new OfflineCachingInterceptor())
            .cache(cache)
            .build();

OfflineCachingInterceptor

public class OfflineCachingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        //Checking if the device is online
        if (!(Util.isOnline())) {
            // 1 day stale
            int maxStale = 86400;
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
}
Sasank Sunkavalli
  • 3,864
  • 5
  • 31
  • 55