Skip to content

Instantly share code, notes, and snippets.

@technoplato
Created March 16, 2017 19:10
Show Gist options
  • Save technoplato/6f589227e5653842f3a35551ea1a6d40 to your computer and use it in GitHub Desktop.
Save technoplato/6f589227e5653842f3a35551ea1a6d40 to your computer and use it in GitHub Desktop.
Overwrite cache headers in Java to hopefully "fix" Picasso caching issue with Firebase storage
public static Client buildOkHttpClient(boolean cacheEnable) {
Cache cache = null;
OkHttpClient client = new OkHttpClient();
if (cacheEnable) {
File cacheDirectory = new File(MainApplication.getInstance().getCacheDir().getAbsolutePath(), "HttpCache");
try {
cache = new Cache(cacheDirectory, CACHE_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
client.setCache(cache);
client.interceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
}
return new OkClient(client);
}
/** Dangerous interceptor that rewrites the server's cache-control header. */
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", String.format("max-age=%d, max-stale=%d", MAX_AGE, MAX_STALE))
.build();
}
};
@technoplato
Copy link
Author

technoplato commented Mar 16, 2017

@technoplato
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment