OkHttp从缓存中排除API

问题描述 投票:0回答:2

我正在使用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 okhttpclient
2个回答
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();

0
投票

Okhttp3为缓存中的URL请求提供Iterator

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

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

© www.soinside.com 2019 - 2024. All rights reserved.