alexey polusov alexey polusov - 1 year ago 687
Java Question

Caching with Retrofit 2.0 and okhttp3

I'm trying to implement caching using Retrofit and OkHttp. Here what I've already done:

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {

@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder request = originalRequest.newBuilder();
Response response = chain.proceed(;
return response.newBuilder()
.header("Cache-Control", "max-age=2419200")

OkHttpClient provideHttpClient(Context context) {

File httpCacheDirectory = new File(context.getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);

HttpLoggingInterceptor oggingInterceptor = new HttpLoggingInterceptor();
return new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)

And then I'm adding this interceptor to the HTTP client:


I've got files inside my responses directory, however when I try to load content without internet connection, it gives me the following error:

Unable to resolve host "": No address associated with hostname

I just want to store my http response somewhere and load it if there are no internet connection.

If there is an Internet connection, I want to rewrite cache.

Answer Source

Setting header this way (exactly 50000) solved the issue.

.header("Cache-Control", String.format("max-age=%d", 50000))