Retrofit caching V1.9.0 - Android OkClient

9
Retrofit Caching - To Catch response by retrofit.

Transcript of Retrofit caching V1.9.0 - Android OkClient

Page 1: Retrofit caching V1.9.0 - Android OkClient

Retrofit Caching - To Catch response by retrofit.

Page 2: Retrofit caching V1.9.0 - Android OkClient

Prerequisites Library dependencies

1. compile 'com.squareup.retrofit:retrofit:1.9.0'2. compile 'com.squareup.okhttp:okhttp:2.3.0'

Page 3: Retrofit caching V1.9.0 - Android OkClient

Why OkHttp?Retrofit uses OkClient that doesn’t have support for

Caching. So we need to give custom OkHttpClient instance.

Page 4: Retrofit caching V1.9.0 - Android OkClient

Steps1. 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))

Page 5: Retrofit caching V1.9.0 - Android OkClient

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.

Page 6: Retrofit caching V1.9.0 - Android OkClient

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 = 0This 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.

Page 7: Retrofit caching V1.9.0 - Android OkClient

Cache Definitionprivate static void createCacheForOkHTTP() { Cache cache = null; cache = new Cache(getDirectory(), 1024 * 1024 * 10); okHttpClient.setCache(cache);}

//returns the file to store cached detailsprivate File getDirectory() {return new File(“location”);}

Page 8: Retrofit caching V1.9.0 - Android OkClient

Cache-Control Valuemax-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.

Page 9: Retrofit caching V1.9.0 - Android OkClient

Change the response header valuesprivate 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(); } };