This class contains the APIClient instance for calling API but here there is one problem while fetching cache. I want to fetch data from cache memory while device is not connected to network.
private static Retrofit retrofit = null;
private static final String CACHE_CONTROL = "Cache-Control";
public static Retrofit getClient(Context context)
{
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(URLS.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(provideOkHttpClient(context))
.build();
}
return retrofit;
}
/**
* Add Client for adding Authentication headers.
* @return Retrofit
*/
public static Retrofit getAthenticationClient()
{
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(URLS.BASE_URL)
.client(ApiIntercepters.AddAuthenticationHeader())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
public static OkHttpClient provideOkHttpClient(Context context)
{
return new OkHttpClient.Builder()
.addNetworkInterceptor(provideCacheInterceptor())
.cache( provideCache(context))
.build();
}
private static Cache provideCache (Context context)
{
Cache cache = null;
try
{
//setup cache
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
cache = new Cache(httpCacheDirectory, cacheSize);
}
catch (Exception e)
{
Log.e( "Injector :-> ", "Could not create Cache!" );
}
return cache;
}
public static Interceptor provideCacheInterceptor ()
{
return new Interceptor()
{
@Override
public Response intercept (Chain chain) throws IOException
{
Response originalResponse = chain.proceed(chain.request());
if (RetrofitDemoApp.hasNetwork()) {
int maxAge = 60; // read from cache for 1 minute
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
}
};
}