简体   繁体   English

使用Retrofit 2和OkHttp 3进行脱机响应缓存

[英]Offline response caching with Retrofit 2 and OkHttp 3

I'm trying to cache response via OkHttp and Retrofit. 我正在尝试通过OkHttp和Retrofit缓存响应。 I understand there are several questions similar to mine but none of those are able to address my issue. 我了解有几个问题与我的类似,但是没有一个能够解决我的问题。

Following is my Interceptor responsible for modifying the headers. 以下是我的拦截器负责修改标头。

private static class CachingControlInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            Response originalResponse = chain.proceed(request);
            return originalResponse.newBuilder()
                    .header("Cache-Control", (UtilityMethods.isNetworkAvailable()) ?
                            "public, max-age=60" :  "public, max-stale=604800")
                    .build();
        }
    }

Now, this works perfectly in the first case - 现在,这在第一种情况下非常有效-

  1. Internet connection is available. Internet连接可用。
  2. A valid response is received and cached. 接收并缓存了有效的响应。
  3. Disconnect the device from the internet. 断开设备与互联网的连接。
  4. Send the same request as previous one within a minute -> Response is same as last 一分钟内发送与上一个相同的请求->响应与上一个相同
  5. Next, send the same request after a minute is complete -> No response ( UnknownHostException ) 接下来,在一分钟后发送相同的请求->无响应( UnknownHostException

This makes the first part ( "public, max-age=60" ) complete. 这样就完成了第一部分( "public, max-age=60" )。

But, somehow, "public, max-age=60" part does not work at all. 但是,以某种方式, "public, max-age=60"部分根本不起作用。

This part should enable okhttp to fetch the a week old stale data when the device is offline but instead, I get UnknownHostException . 该部分应使okhttp能够在设备脱机时获取为期一周的过时数据,但我却得到UnknownHostException

I think this is what you are looking for : 我认为这是您要寻找的:

.header("Cache-Control", (UtilityMethods.isNetworkAvailable()) ?
            "public, max-age=60" :  "public, only-if-cached, max-stale=604800")

This adds the only-if-cached directive for when the network is unavailable. 这会在网络不可用时添加“ only-if-cached指令。 This only accepts the response if it is in the cache. 如果它在缓存中,则仅接受响应。

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

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