【问题标题】:Is Retrofit+Okhttp using httpCaching as a default in Android?Retrofit+Okhttp 在 Android 中是否默认使用 httpCaching?
【发布时间】:2014-03-01 21:05:19
【问题描述】:

我在我们的一个应用程序中使用了retrofitokhttp

对于 Retrofit 的默认行为,我真的找不到很好的解释。

如果 Okhttp 在类路径上,它将被自动使用。但据我所见,默认的 HttpResponseCache 为空。

我是否需要使用 Retrofit 和 Okhttp 显式启用缓存?

【问题讨论】:

    标签: android http http-caching retrofit okhttp


    【解决方案1】:

    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();
    

    documentation

    【讨论】:

    • setCache在3中不存在,所以可以使用new OkHttpClient.Builder().cache(cache).build();
    • 谢谢@frostymarvelous
    【解决方案2】:

    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));
    

    代码基于Jesse Wilsons example on Github

    【讨论】:

    【解决方案3】:

    您应该手动创建 OkHttpClient 并按照您的喜好进行配置。在这种情况下,您应该安装缓存。一旦你创建了一个 OkClient 并将它传递给 Retrofit 的 RestAdapter.Builder

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

    【讨论】:

    • 我添加了我在单独答案中使用的代码,因为我认为这对其他人来说也会很有趣。由于我从您的示例中复制了它,我希望代码没问题。
    • stackoverflow.com/questions/22445177/… 表示不需要再配置缓存了。这是正确的吗?
    猜你喜欢
    • 2015-08-26
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2021-02-08
    • 2015-03-25
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多