Modify online and offline caching

my App mode is 2: 1.Online 2.Offline I need a retrofitted cache with the following requirements:

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

      

I am using this code

//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();

      

but this code doesn't work offline if "public, max-age =" + 5 convert to "public, max-age =" + 5000 offline, but online catch is used, I need online mode, just use api online

+3


source to share





All Articles