我在我们的应用程序中使用了retrofit和okhttp。是改造+ Okhttp使用httpCaching作为默认的Android?
我无法真正找到对Retrofit的默认行为的一个很好的解释。
如果Okhttp在类路径上,它将被自动使用。但据我所见,默认的HttpResponseCache为null。
我是否需要使用Retrofit和Okhttp显式启用缓存?
我在我们的应用程序中使用了retrofit和okhttp。是改造+ Okhttp使用httpCaching作为默认的Android?
我无法真正找到对Retrofit的默认行为的一个很好的解释。
如果Okhttp在类路径上,它将被自动使用。但据我所见,默认的HttpResponseCache为null。
我是否需要使用Retrofit和Okhttp显式启用缓存?
您应该手动创建您的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));
为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();
setCache在3中不存在。所以你可以使用'新的OkHttpClient.Builder()。缓存(缓存).build();' – frostymarvelous
Thanks @frostymarvelous –
我说我在不同的答案中使用的代码,因为我认为这将是为其他人也很有趣。由于我从你的例子中复制了它,我希望代码可以。 – Janusz
http://stackoverflow.com/questions/22445177/trying-to-make-use-of-httpcache-android说,没有必要再配置缓存。它是否正确? – Janusz