为在线和离线模式缓存的改造

时间:2017-07-31 13:21:48

标签: android caching retrofit offline

我的App 2模式:1.Online 2.Offline 我需要一个具有以下要求的改造缓存:

if (mobile is connect to internet){
  //call api online and along with without catch
}else if (mobile is disconnect){
  //use cached api call 
}

我使用此代码

//catch size
long SIZE_OF_CACHE = 1000 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(new File(context.getCacheDir(), "http"), SIZE_OF_CACHE);


OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addNetworkInterceptor(new Interceptor() {
     @Override
     public Response intercept(Chain chain) throws IOException {
          Request original = chain.request();
          Request.Builder requestBuilder = original.newBuilder()
                 .header("Content-Type", "application/json; charset=utf-8")
                 .header("Version-Application", String.valueOf(BuildConfig.VERSION_CODE))
                 .method(original.method(), original.body());


          if (!Constants.userConfig.token.isEmpty()) {
              requestBuilder.header("Authorization-Token", Constants.userConfig.token);
          }

          Request request = requestBuilder.build();
          Response response = chain.proceed(request);

          if (NetworkUtils.isNetworkAvailable(AppController.getInstance().getApplicationContext())) {
               Log.i("====== state" , "is online");
               return response.newBuilder()
                      .header("Cache-Control", "public, max-age=" + 5)
                      .removeHeader("Pragma")
                      .build();
          } else {
               Log.i("====== state" , "is offline");
               return response.newBuilder()
                      .header("Cache-Control", "public, only-if-cached, max-stale=" + 3600000)
                      .removeHeader("Pragma")
                      .build();
          }

     }
 });

 //set 300 for don't send again and again in break point server
 httpClient.connectTimeout(300, TimeUnit.SECONDS);
 httpClient.readTimeout(300, TimeUnit.SECONDS);
 httpClient.writeTimeout(300, TimeUnit.SECONDS);

 httpClient.addNetworkInterceptor(new StethoInterceptor());//for stetho facebook library
 httpClient.cache(cache);
 httpClient.retryOnConnectionFailure(true);

 OkHttpClient client = httpClient.build();
 retrofit = new Retrofit.Builder()
                .baseUrl(URL_API)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

但此代码不适用于离线 如果" public,max-age =" + 5转换为" public,max-age =" + 5000 离线模式工作但在线模式使用catch, 我需要在线模式才能使用api online

0 个答案:

没有答案