2014-02-05 27 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 –