【问题标题】:Disable Cache of okhttp禁用okhttp的缓存
【发布时间】:2017-08-05 13:58:11
【问题描述】:

我知道禁用 okhttp 的缓存是调用Request.cacheControl(CacheControl.FORCE_NETWORK)。是否可以从 OkHttpClient.class 设置 cacheControl?因为我的所有请求都有 1 个客户。所以我想通过从 okhttpClient 禁用它来禁用所有请求的缓存

【问题讨论】:

    标签: android caching okhttp3 okhttp


    【解决方案1】:

    使用它来构建 Retrofit 并提供缓存,因为null API 不会缓存任何内容。

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

    【讨论】:

    • 什么是 mCache?
    • 它是一个缓存文件,如果你想提供缓存你可以定义它。
    • 如果我不使用readTimeoutconnectTimeoutwriteTimeout而只使用cache()可以吗?
    • 是的,它是一个构建器类,您可以完全选择传递任何所需的值。
    【解决方案2】:

    为你的客户端添加拦截器,并在拦截器中添加缓存控制头。检查下面的示例代码:

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

    【讨论】:

    • 你需要保留对newBuilder()结果的引用。
    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2018-05-31
    • 2015-01-01
    • 2017-05-07
    • 2015-12-20
    • 2014-09-23
    • 2021-12-30
    • 2016-02-18
    相关资源
    最近更新 更多