Retrofit uses OkClient for the Http operations, but caching is possible only in OkHttpClient. Here I have explained how to cache the response by changing the headers.
3. Why OkHttp?
Retrofit uses OkClient that doesn’t have support for
Caching. So we need to give custom OkHttpClient
instance.
4. Steps
1. Cache details to the OkHttpClient instance.
2. Caching is decided by server response headers.
3. If server response has no headers or we have to
change the headers. We can do that by Interceptors.
4. Set that to the OkHttpClient instance by
okHttpClient.networkInterceptors().add(interceptorInstance);
5. Set the OkClient instance by passing OkHttpClient
instance to the RestAdapter.
restAdapter.setClient(new OkClient(okHttpClient))
5. Warning!!
Its dangerous to change the server response
headers. Always try to give the headers in the server
response. For some extreme cases only try to implement
by ResponseInterceptors.
6. How its Caching?
Retrofit handles caching by the response Headers.
Cache-Control does the magic.
example
Cache-Control : max-age = 120, only-if-cached, max-
stale = 0
This header will cache the value for 120 seconds and also the api request will
try to check for the cache before trying to hit.
List of Cache-Control headers to play.
7. Cache Definition
private static void createCacheForOkHTTP() {
Cache cache = null;
cache = new Cache(getDirectory(), 1024 * 1024 * 10);
okHttpClient.setCache(cache);
}
//returns the file to store cached details
private File getDirectory() {
return new File(“location”);
}
8. Cache-Control Value
max-age - Timeout value in seconds to hit again.
no-cache - Do not use the cache.
no-store - Do not store the cache.
only-if-cached - Check the cache before trying to hit.
9. Change the response header values
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new
Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", String.format("max-age=%d, only-if-cached, max-
stale=%d", 120, 0))
.build();
}
};