alexey polusov alexey polusov - 4 months ago 444
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(request.build());
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", "max-age=2419200")
.build();
}
};

@Provides
@Singleton
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();
oggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(oggingInterceptor).build();
}


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

.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)

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 "example.com": 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

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

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