OkHttp does not cache responses on Android

I am using retrofit 1.8.0, okhttp 2.1.0 and okhttp-urlconnection 2.1.0, I want to cache the responses received from the server and use them when there is no internet connection, this is my code:

RequestInterceptor requestInterceptor = new RequestInterceptor() {

    @Override
    public void intercept(RequestFacade request) {

        request.addHeader("Accept", "application/json");
        if (Utils.isNetworkAvailable(HancoApplication.this)) {

            int maxAge = 60; // read from cache for 1 minute
            request.addHeader("Cache-Control", "public, max-age=" + maxAge);
        } else {

            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            request.addHeader("Cache-Control","public, only-if-cached, max-stale=" + maxStale);
        }
    }
};
OkHttpClient okHttpClient = new OkHttpClient();
File cacheDir = new File(getCacheDir(), "responseCache");
Cache cache = null;
try {

    cache = new Cache(cacheDir, 1024 * 1024 * 12);
    okHttpClient.setCache(cache);
} catch (IOException e) {

    e.printStackTrace();
}
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Const.API_URL).setClient(new OkClient(okHttpClient)).setRequestInterceptor(requestInterceptor).build();
mWebApi = restAdapter.create(WebApi.class);

      

when i get the same request without internet over the phone, this is what it returns: HTTP / 1.1 504 Invalid request (only in case of caching) OkHttp-Response-Source: NONE

I can't figure out what is wrong with my code, all resources on the internet use the same code!

+3


source to share





All Articles