2016-10-11 69 views
6

我試圖設置緩存進行Retrofit,以便它不必不斷地檢索數據。我跟着this SO,因爲它似乎是在我需要的正確方向。OkHttpClient無法解析方法setCache

我有以下的(等同從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)返回錯誤cannot resolve method setCache

我在做什麼錯在這裏?我有改進2.1.0和okhttp3 3.4.1

回答

12

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(); 
+0

我收到一個錯誤無法解析符號'REWRITE_CACHE_CONTROL_INTERCEPTOR' –