【问题标题】:Caching data with retrofit 2使用改造 2 缓存数据
【发布时间】:2018-12-03 01:39:08
【问题描述】:

我也在尝试使用改造以离线模式访问我的数据,但它没有发生。
代码没有问题,但它不起作用。

两种 WiFi 状态的日志数据相同。

OkHttpClient client = new OkHttpClient
                .Builder()
                .addInterceptor(logging)
                .addInterceptor(new Interceptor() {
                    @Override public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (isNetworkAvailable(context,ConnectivityManager.TYPE_WIFI)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                            Log.d("data",request.toString());
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                            Log.d("data1",request.toString());

                        }
                        return chain.proceed(request);
                    }
                })
                .cache(new Cache(httpCacheDirectory, 10 * 1024 * 1024)) // 10 MB
                .build();

【问题讨论】:

    标签: java android caching retrofit2


    【解决方案1】:

    这应该适合你。

        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                .cache(new Cache(getyourapplicationcontext.getCacheDir(), 10 * 1024 *1024))
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    if (NetworkUtil.isDeviceConnectedToInternet(getyourapplicationcontext)) {
                        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                    } else {
                        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                    }
                    return chain.proceed(request);
                })
                .build();``
    

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 1970-01-01
      • 2018-02-04
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2018-01-18
      • 2023-03-08
      相关资源
      最近更新 更多