2014-02-05 26 views

回答

7

您應該手動創建您的OkHttpClient並將其配置爲您喜歡的方式。在這種情況下,你應該安裝一個緩存。一旦你創建了OkClient並將其傳遞給Retrofit的RestAdapter.Builder

另外,不對HTTP POST請求進行緩存。但是,GET將被緩存。

+1

我說我在不同的答案中使用的代碼,因爲我認爲這將是爲其他人也很有趣。由於我從你的例子中複製了它,我希望代碼可以。 – Janusz

+1

http://stackoverflow.com/questions/22445177/trying-to-make-use-of-httpcache-android說,沒有必要再配置緩存。它是否正確? – Janusz

8

棄用OkHttpClient V2.0.0和更高

傑西·威爾遜指出,你需要創建自己的緩存。
以下代碼應該創建一個10MB緩存。

File httpCacheDirectory = new File(application.getApplicationContext() 
    .getCacheDir().getAbsolutePath(), "HttpCache"); 

HttpResponseCache httpResponseCache = null; 
try { 
    httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024); 
} catch (IOException e) { 
    Log.e(getClass().getSimpleName(), "Could not create http cache", e); 
} 

OkHttpClient okHttpClient = new OkHttpClient(); 
okHttpClient.setResponseCache(httpResponseCache); 
builder.setClient(new OkClient(okHttpClient)); 

該代碼基於Jesse Wilsons example on Github

+0

如果這是在帖子上設置,它會被忽略?因爲我設置它在我的一般建設者,這是用於每個請求 – Lion789

+0

http://stackoverflow.com/questions/22445177/trying-to-make-use-of-httpcache-android我實際上得到這個錯誤...如果我不使用httpResponseCache.install它錯誤,新的HttpResponseCache不能在外面使用...它不是公開的.. – Lion789

+2

是不是一個10MB緩存? –

15

爲OkHttpClient v2的正確實施:

int cacheSize = 10 * 1024 * 1024; // 10 MiB 
File cacheDir = new File(context.getCacheDir(), "HttpCache"); 
Cache cache = new Cache(cacheDir, cacheSize); 
OkHttpClient client = new OkHttpClient.Builder() 
    .cache(cache) 
    .build(); 

看到documentation

+3

setCache在3中不存在。所以你可以使用'新的OkHttpClient.Builder()。緩存(緩存).build();' – frostymarvelous

+0

Thanks @frostymarvelous –