I am using retrofit 1.8.0, okhttp 2.1.0 and okhttp-urlconnection 2.1.0, I want to cache the responses I get from 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 excute the same request without internet on the phone this is what it returns : HTTP/1.1 504 Unsatisfiable Request (only-if-cached) OkHttp-Response-Source: NONE
I can't figure out whats wrong with my code, all the resources on the internet uses the same code!