【问题标题】:Bypass okHttp Cache to get a network response and then update the cache绕过okHttp缓存获取网络响应然后更新缓存
【发布时间】:2016-08-03 07:51:59
【问题描述】:

我正在使用 Retrofit2 和 OKHttp 缓存 HTTP 响应。 这是我的代码:

    int cacheSize = 10 * 1024 * 1024;
    Cache cache = new Cache(application.getCacheDir(), cacheSize);

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().
cache(cache).addNetworkInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();

我正在从我们的后端 REST API 获取响应标头 Cache-control 和 Expires。

现在我想通过绕过 Expires 标头来获取服务器响应。 请帮我解决这个问题。

【问题讨论】:

    标签: android http retrofit okhttp http-caching


    【解决方案1】:

    将此标头添加到您的 HTTP 请求中:

    Cache-Control: no-cache
    

    您可以使用 Retrofit 的 @Header 或 OkHttp interceptor 来做到这一点。

    【讨论】:

    • 每当我需要刷新数据时,我都会调用服务器,但刷新的数据也应该被缓存以备下次使用,直到我想刷新数据。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2017-08-12
    • 2018-06-19
    • 2016-03-20
    • 2018-05-31
    • 2022-01-09
    • 2016-02-18
    • 2018-07-17
    相关资源
    最近更新 更多