我用改造和okhttp在我们的应用程序之一.
我无法找到Retrofit默认行为的好解释.
如果Okhttp在类路径上,它将自动使用.但据我所知,默认的HttpResponseCache为null.
我是否需要使用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并根据需要进行配置.在这种情况下,您应该安装缓存.一旦你有了创建一个OkClient并将其传递给Retrofit的RestAdapter.Builder
此外,没有HTTP POST请求的缓存.但是,GET将被缓存.
已弃用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));
该代码基于Github上的Jesse Wilsons示例.