1

I'm trying to implement caching using Retrofit and OkHttp. I am getting '504 Unsatisfiable Request (only-if-cached)' as Error when offline.

OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);

        if (isDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                .addInterceptor(OFFLINE_INTERCEPTOR)
                .cache(provideCache());


        OkHttpClient client = builder.build();




        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        reqinterface = retrofit.create(MyApiInterface.class);

  private static Cache provideCache(){
    Cache cache = null;
    try{

        cache = new Cache(new File(context.getCacheDir(),"baskin-cache"),
                10*1024*1024);
    }catch (Exception e){
        Log.i("zacharia","Could not create Cache");
    }
    return  cache;
}
  private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");

        if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + 120)
                    .build();
        } else {
            return originalResponse;
        }
    }
};

private static final Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!isOnline()) {
            Log.d("zacharia", "rewriting request");

            int maxStale = 60 * 60 * 24 * 7; // tolerate 4-weeks stale
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
};

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

When online, I am getting 'D/OkHttp: Cache-Control: public, max-age=120' in the log. When offline , 'D/OkHttp: <-- 504 Unsatisfiable Request (only-if-cached)'

zacharia
  • 1,083
  • 2
  • 10
  • 22

1 Answers1

0

You could try to debug methods okhttp3.internal.cache.CacheInterceptor#intercept(Chain) and okhttp3.Cache#get(Request) to see why previous response is not returned.

Milanka
  • 1,742
  • 19
  • 15