【问题标题】:OkHttp exclude APIs from cachingOkHttp 从缓存中排除 API
【发布时间】:2018-05-15 09:21:05
【问题描述】:

我正在使用 Retrofit 和 OkHttp 客户端进行网络调用。我的服务器支持 Etag 缓存,我已将缓存添加到 okHttp 客户。有些 API 我不想缓存

这是我的okHttpClient 配置

    OkHttpClient okHttpClient(Context context,
                                         HttpLoggingInterceptor loggingInterceptor,Cache okHttpCache) {
            final OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .cache(okHttpCache)
            return builder.build();
        }


    Cache cache(Context context) {
    return new Cache(new File(context.getCacheDir(), "cache"),10 * 1024 * 1024);
     }

我可以忽略缓存中的某些 API 吗?

【问题讨论】:

    标签: android retrofit okhttp3 http-caching okhttp


    【解决方案1】:

    Okhttp3 为缓存中的 urls 请求提供一个迭代器

    public Iterator<String> urls() throws IOException {
      hasNext();
      next();
      remove();
    }
    

    您可以简单地使用它来检查感兴趣的 API 并忽略它。 见文档http://java.sun.com/javase/6/docs/api/java/util/Iterator.html?is-external=true

    【讨论】:

      【解决方案2】:

      如果您只使用 OkHttp 库,那么您可以将缓存控制策略指定为 CacheControl.FORCE_NETWORK 到您的请求对象。更多信息在这里:https://github.com/square/okhttp/issues/1496

      如果您将 OkHttp 与 Retrofit 结合使用,您可以在接口内的请求定义方法中添加 Cache-Control: no-cache 标头: (示例中的拼写已更新)

      @Headers("Cache-Control: no-cache")
      @GET("users/me")
      Call<User> getUser();
      

      【讨论】:

      • 好的。我正在使用 OkHttp 和 Retrofit,目前我刚刚将缓存添加到 okHttp 配置中,如我的代码所示。它会为所有 API 启用缓存吗?无论我不想要哪个,我都可以用@Headers("Cahce-Contol: no-cache") 覆盖?
      • 如果您的后端应用程序处理缓存策略通过了请求标头,那么可以。如果您的服务器不支持它,那么有基于请求拦截器实现的解决方法。
      • 如果您的服务器支持 Etag 缓存机制,我们可以使用此配置对吗?
      猜你喜欢
      • 2018-02-25
      • 2017-02-03
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      相关资源
      最近更新 更多