【问题标题】:Caching network requests with Okhttp3.0 and retrofit2使用 Okhttp3.0 和 retrofit2 缓存网络请求
【发布时间】:2017-03-13 12:27:42
【问题描述】:

我在我的 android 应用程序中为 REST API 使用 Retrofit2 和 OKHTTP3。我的要求是我必须缓存请求才能在离线模式下使用应用程序。问题是我能够缓存请求。但是当用户再次上线时,应该从后端重新获取数据,它不应该提供缓存的响应。我怎样才能做到这一点。下面是我的网络拦截器

网络拦截器

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


            if (Util.isOnline()) {
                request = request.newBuilder()
                        .header("Cache-Control", "only-if-cached")
                        .build();
            } else {
                request = request.newBuilder()
                        .header("Cache-Control", "public, max-stale=2419200")
                        .build();
            }

        Response response= chain.proceed(request);
        return response.newBuilder()
                .header("Cache-Control", "max-age=86400")
                .build();
    }
}

【问题讨论】:

    标签: android caching retrofit2 okhttp3 okhttp


    【解决方案1】:

    参考这个答案link OkHttp拦截器是离线访问缓存的正确方式:

    【讨论】:

      【解决方案2】:

      知道了。如果设备离线,我将 Cache-Control 标头设置为 "public, only-if-cached, max-stale=86400" (这将设置过期时间为 1 天)。现在,如果设备在线,它将从服务器重新获取。

      OkHttpClient

      okHttpClient = new OkHttpClient.Builder()
                  .addInterceptor(new OfflineCachingInterceptor())
                  .cache(cache)
                  .build();
      

      离线缓存拦截器

      public class OfflineCachingInterceptor implements Interceptor {
          @Override
          public Response intercept(Chain chain) throws IOException {
      
              Request request = chain.request();
              //Checking if the device is online
              if (!(Util.isOnline())) {
                  // 1 day stale
                  int maxStale = 86400;
                  request = request.newBuilder()
                          .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                          .build();
              }
      
              return chain.proceed(request);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 2017-10-02
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多