对于 Retrofit 的默认行为,我真的找不到很好的解释。
如果 Okhttp 在类路径上,它将被自动使用。但据我所见,默认的 HttpResponseCache 为空。
我是否需要使用 Retrofit 和 Okhttp 显式启用缓存?
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();
见文档
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));
您应该手动创建 OkHttpClient 并按照您的喜好进行配置。在这种情况下,您应该安装缓存。一旦你创建了一个OkClient并将其传递给 Retrofit 的RestAdapter.Builder
此外,没有缓存 HTTP POST 请求。但是,GET 将被缓存。