Skip to content

Instantly share code, notes, and snippets.

@Cristo86
Created July 6, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cristo86/66c23306a60b21cf79ab2b31ce12b626 to your computer and use it in GitHub Desktop.
Save Cristo86/66c23306a60b21cf79ab2b31ce12b626 to your computer and use it in GitHub Desktop.
Building an OkHttpClientWithCache v1
// By https://github.com/newfivefour/BlogPosts/blob/master/android-retrofit2-okhttp3-cache-network-request-offline.md
OkHttpClient client = new OkHttpClient
.Builder()
.cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
.addInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (App.isNetworkAvailable()) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
}
return chain.proceed(request);
}
})
.build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment