Retrofit + Okhttp是否使用httpCaching作为Android的默认设置?

Jan*_*usz 9 android http http-caching retrofit okhttp

我用改造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)

文档

  • setCache在3.中不存在.所以你可以使用`new OkHttpClient.Builder().cache(cache).build();` (3认同)

Jan*_*usz 8

已弃用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示例.

  • 是不是10MB缓存? (2认同)

Jes*_*son 7

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

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