OkHttpClient 无法解析方法 setCache

OkHttpClient cannot resolve method setCache

我正在尝试为 Retrofit 设置缓存,这样它就不必经常检索数据。我遵循 this SO 因为它似乎是我需要的正确方向。

我有以下内容(与 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);

但是,client.setCache(cache)returns一个错误cannot resolve method setCache

我在这里做错了什么?我有改造 2.1.0 和 okhttp3 3.4.1

在 3.x 中,OkHttpClient 上的一堆方法被移到了 OkHttpClient.Builder 上的方法中。你想要这样的东西:

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();
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();
            }
        }
    };