Possible Duplicate
I'm trying to set up the cache for OkHttp3. I am working on a mapping application where request are sending continuously to fetch map tiles/data. I have setup cache as follow:
try {
if (mContext.getExternalCacheDir() != null) {
String mapsCacheDirectoryPath = getMapsCacheDirectoryPath(mContext);
File httpCache = new File(mapsCacheDirectoryPath + "/tile_cache");
Cache okTileCache = new Cache(httpCache, 100 * 1024 * 1024);
okClient.setCache(okTileCache);
}
} catch (Exception e) {
e.printStackTrace();
}
And i am also using Interceptor to add Cache-Control header as:
okClient.interceptors().add(
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
String cacheHeaderValue = isInternetConnectionAvailable(context, false)
? "public, max-age=2419200"
: "public, only-if-cached, max-stale=2419200";
Request request = originalRequest.newBuilder().build();
Response response = chain.proceed(request);
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheHeaderValue)
.build();
}
}
);
okClient.networkInterceptors().add(
new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
String cacheHeaderValue = isInternetConnectionAvailable(context, false)
? "public, max-age=2419200"
: "public, only-if-cached, max-stale=2419200";
Request request = originalRequest.newBuilder().build();
Response response = chain.proceed(request);
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheHeaderValue)
.build();
}
}
);
Now when i run app with Wifi enabled. It starts caching data in specified storage location. But When i turn off wifi and restart app it do not load/show data from cache. When request is sent i onFailure gets called with error:
java.net.ConnectException: Failed to connect to /192.168.290.75:8787
It is suggested that i should close response body to make it work so i have added response.body().close() but still got the same error. What am i doing wrong?