client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT, TimeUnit.MINUTES);
client.setReadTimeout(TIMEOUT_READ, TimeUnit.MINUTES);
client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
client.networkInterceptors().add(HTTP_LOG);

File httpCacheDirectory = new File(MyApplication.getContext().getCacheDir(), "responses");
Cache cache = new Cache(httpCacheDirectory, CACHE_SIZE);

client.setCache(cache);

 - With cache interceptor like this :

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (NetworkUtil.isNetworkOnline()) {
            int maxAge = MAX_AGE; // read from cache for 1 minute
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * MAX_STALE_DAY; // tolerate 4-weeks stale
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }

};
private static final Interceptor HTTP_LOG = new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Logger.i("REQUEST INFO", request.toString());
        Response response = chain.proceed(request);
        Logger.i("OKHTTP", response.toString());
        return response;
    }
};
Advertisements