Jan*_*usz 9 android http http-caching retrofit okhttp
我无法找到Retrofit默认行为的好解释.
如果Okhttp在类路径上,它将自动使用.但据我所知,默认的HttpResponseCache为null.
我是否需要使用Retrofit和Okhttp显式启用缓存?
e.s*_*kin 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();
Run Code Online (Sandbox Code Playgroud)
看文档
已弃用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));
Run Code Online (Sandbox Code Playgroud)
该代码基于Github上的Jesse Wilsons示例.
您应该手动创建OkHttpClient并根据需要进行配置.在这种情况下,您应该安装缓存.一旦你有了创建一个OkClient并将其传递给Retrofit的RestAdapter.Builder
此外,没有HTTP POST请求的缓存.但是,GET将被缓存.
| 归档时间: |
|
| 查看次数: |
10630 次 |
| 最近记录: |