代码之家  ›  专栏  ›  技术社区  ›  Mena

改装离线兑现返回空响应。body())

  •  1
  • Mena  · 技术社区  · 6 年前

    我试过这个 link 而这 link 构建离线改造缓存。

    问题是,如果我将手机置于飞行模式,那么response.body()始终为空。

    以下是我的代码:

    OkHttpClient client = new OkHttpClient
      .Builder()
      .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
      .addInterceptor(new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
          Request request = chain.request();
          if (App.isNetworkAvailable()) {
            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();
    
     retrofit = new retrofit2.Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(okHttpClient)
                        .build();
    

     final RetrofitServiceInterface service = RetrofitClient.getRetrofitInstance(this).create(RetrofitServiceInterface.class);
            Call<List<RetroPhoto>> call = service.getAllPhotos();
            call.enqueue(new Callback<List<RetroPhoto>>() {
                @Override
                public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
    
                    generateDataList(response.body()); ////HERE!!!!
                }
    
                @Override
                public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
                }
            });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   user8873209    6 年前

    试试这个代码

            int cacheSize = 10 * 1024 * 1024; // 10 MB
    
            Cache cache = new Cache(new File(getApplication().getCacheDir(),"someIdentifier"), cacheSize);
    
            Interceptor offlineCacheInterceptor = new Interceptor() {
                @Override
                public Response intercept (Chain chain) throws IOException {
                    Request request = chain.request();
    
                    if(!App.isNetworkAvailable()) {
                        CacheControl cacheControl = new CacheControl.Builder()
                                .maxStale(30, TimeUnit.DAYS)
                                .build();
    
                        request = request.newBuilder()
                                .cacheControl(cacheControl)
                                .build();
                    }
                    return chain.proceed( request );
                }
            };
    
    推荐文章