9

我在我们的一个应用程序中使用了改造okhttp

对于 Retrofit 的默认行为,我真的找不到很好的解释。

如果 Okhttp 在类路径上,它将被自动使用。但据我所见,默认的 HttpResponseCache 为空。

我是否需要使用 Retrofit 和 Okhttp 显式启用缓存?

4

3 回答 3

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

文档

于 2014-07-01T15:51:02.627 回答
8

OkHttpClient v2.0.0 及更高版本已弃用

正如 Jesse Wilson 指出的那样,您需要创建自己的缓存。
下面的代码应该创建一个 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));

该代码基于Github 上的 Jesse Wilsons 示例

于 2014-02-06T07:37:35.453 回答
7

您应该手动创建 OkHttpClient 并按照您的喜好进行配置。在这种情况下,您应该安装缓存。一旦你创建了一个OkClient并将其传递给 Retrofit 的RestAdapter.Builder

此外,没有缓存 HTTP POST 请求。但是,GET 将被缓存。

于 2014-02-06T06:36:05.083 回答