9

I'm trying to set a cache for Retrofit so that it does not have to retrieve the data constantly. I followed this SO as it appears to be in the right direction of what I need.

I have the following (which is identical from the SO)

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10*1024*1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
client.setCache(cache);

However, client.setCache(cache) returns an error cannot resolve method setCache.

What am I doing wrong here? I have retrofit 2.1.0 and okhttp3 3.4.1

Community
  • 1
  • 1
user3277633
  • 1,891
  • 6
  • 28
  • 48

2 Answers2

16

In 3.x a bunch of methods on OkHttpClient were moved into methods on OkHttpClient.Builder. You want something like this:

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

OkHttpClient client = new OkHttpClient.Builder()
    .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
    .cache(cache)
    .build();
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
0
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10*1024*1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);

OkHttpClient client = new OkHttpClient.Builder()
    .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
    .cache(cache)
    .build();

/////////and

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