Skip to content

Instantly share code, notes, and snippets.

@Gnzlt
Created December 5, 2016 11:20
Show Gist options
  • Save Gnzlt/000d561576d47bebfb09370e8fc51ffe to your computer and use it in GitHub Desktop.
Save Gnzlt/000d561576d47bebfb09370e8fc51ffe to your computer and use it in GitHub Desktop.
Basic Retrofit RestClient for offline cache using interceptors
public class RestClient {
private static MyEndpoints sMyEndpoints;
public static void init(Context context) {
sMyEndpoints = getRetrofit(context).create(MyEndpoints.class);
}
private static Retrofit getRetrofit(Context context) {
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getHttpClient(context))
.build();
}
private static OkHttpClient getHttpClient(Context context) {
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
.addInterceptor(getCacheInterceptor(context))
.cache(getCache(context));
return httpBuilder.build();
}
private static Interceptor getCacheInterceptor(final Context context) {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
if (!Utils.isNetworkAvailable(context)) {
Request request = chain.request();
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(1, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
return chain.proceed(request);
} else {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(1, TimeUnit.HOURS)
.build();
return response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build();
}
}
};
}
private static Cache getCache(Context context) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
return new Cache(context.getCacheDir(), cacheSize);
}
public static MyEndpoints getApiService() {
return sMyEndpoints;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment