Skip to content

Instantly share code, notes, and snippets.

@vudunguit
Created May 10, 2018 11:08
Show Gist options
  • Save vudunguit/838b4c290046dff73ad8007ce06b4b73 to your computer and use it in GitHub Desktop.
Save vudunguit/838b4c290046dff73ad8007ce06b4b73 to your computer and use it in GitHub Desktop.
Cache OkHttpClient
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(new RewriteRequestInterceptor())
.addNetworkInterceptor(new RewriteResponseCacheControlInterceptor())
public class RewriteRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
int maxStale = 60 * 60 * 24 * 5;
Request request;
if (NetworkUtils.isNetworkAvailable()) {
request = chain.request();
} else {
request = chain.request().newBuilder().header("Cache-Control", "max-stale=" + maxStale).build();
}
return chain.proceed(request);
}
}
public class RewriteResponseCacheControlInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
int maxStale = 60 * 60 * 24 * 5;
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().header("Cache-Control", "public, max-age=120, max-stale=" + maxStale).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment