Created
May 10, 2018 11:08
-
-
Save vudunguit/838b4c290046dff73ad8007ce06b4b73 to your computer and use it in GitHub Desktop.
Cache OkHttpClient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder() | |
.cache(cache) | |
.addInterceptor(new RewriteRequestInterceptor()) | |
.addNetworkInterceptor(new RewriteResponseCacheControlInterceptor()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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