Skip to content

Instantly share code, notes, and snippets.

@vbsteven
Created November 19, 2015 10:54
Show Gist options
  • Save vbsteven/973eab176e836399bb8a to your computer and use it in GitHub Desktop.
Save vbsteven/973eab176e836399bb8a to your computer and use it in GitHub Desktop.
Retrofit ApiModule I frequently use to provide custom app-level http caching
package io.quantus.winterinantwerpen.api;
import android.content.Context;
import android.location.LocationManager;
import android.util.Log;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.quantus.winterinantwerpen.language.LanguageManager;
import io.quantus.winterinantwerpen.util.ConnectivityHelper;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
@Module
public class ApiModule {
@Provides
ApiService provideApiService(Context context, LanguageManager languageManager) {
OkHttpClient client = new OkHttpClient();
Cache responseCache = new Cache(new File(context.getCacheDir(), "http"), 1024 * 1024 * 10); // 10 MB cache size
client.setCache(responseCache);
client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.networkInterceptors().add(mCacheControlInterceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(String.format("https://api.winterapp.be/%s/", languageManager.getLocale()))
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiService.class);
}
private static final Interceptor mCacheControlInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Add Cache Control only for GET methods
if (request.method().equals("GET")) {
if (ConnectivityHelper.isConnected()) {
Log.d("CacheControlInterceptor", "intercept connected");
// 1 day
request.newBuilder()
.header("Cache-Control", "only-if-cached")
.build();
} else {
Log.d("CacheControlInterceptor", "intercept not connected");
// 4 weeks stale
request.newBuilder()
.header("Cache-Control", "public, max-stale=2419200")
.build();
}
}
Response response = chain.proceed(request);
// Re-write response CC header to force use of cache
return response.newBuilder()
.header("Cache-Control", "public, max-age=86400") // 1 day
.header("Pragma", "public")
.build();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment