As per Retrofit 1.9.0
which uses OkClient
does not have Caching support. We have to use OkHttpClient
instance by Square OkHttpClient
library.
You can compile by compile 'com.squareup.okhttp:okhttp:2.3.0'
Before everything retrofit caches by response headers like
Cache-Control:max-age=120,only-if-cached,max-stale
** 120 is seconds.
You can read more about headers here.
Caching headers are mostly instructed by server response. Try to implement cache headers in servers. If you don't have an option, yes retrofit has it.
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();
}
};
Where to cache:
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”);
}
Add interceptor to the OkHttpClient instance:
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
And finally add OkHttpClient to the RestAdapter:
RestAdapter.setClient(new OkClient(okHttpClient));
And you can go through this slide for more reference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…