简体   繁体   English

禁用 okhttp 缓存

[英]Disable Cache of okhttp

i know to disable cache of okhttp is to call Request.cacheControl(CacheControl.FORCE_NETWORK) .我知道禁用 okhttp 缓存是调用Request.cacheControl(CacheControl.FORCE_NETWORK) Is it possible to set the cacheControl from OkHttpClient.class?是否可以从 OkHttpClient.class 设置 cacheControl? Because i have 1 client for all my request.因为我的所有请求都有 1 个客户。 So i want to disable cache for all the request by disabling it from the okhttpClient所以我想通过从 okhttpClient 禁用它来禁用所有请求的缓存

Use this to build Retrofit and provide cache as null the API will not cache anything.使用它来构建 Retrofit 并提供缓存为null API 不会缓存任何内容。

private OkHttpClient createOkHttpClient() {
    return new OkHttpClient.Builder()
            ...
            .cache(null)
            .build();
}

add interceptor to your client, and add cache control header in interceptor.check sample code below:将拦截器添加到您的客户端,并在拦截器中添加缓存控制标头。检查以下示例代码:

    Interceptor interceptor = new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder().addHeader("Cache-Control", "no-cache");
            request = builder.build();
            return chain.proceed(request);
        }
    };

    OkHttpClient mClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM