Retrofit Offline cashing returns a null response.body()

后端 未结 1 1690
情深已故
情深已故 2021-01-24 23:45

I tried this link and this link to construct an offline Retrofit cache.

The problem is that if I put the phone in Airplane mode, the Response.body() is always null.

相关标签:
1条回答
  • 2021-01-25 00:29

    try this code

            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 );
                }
            };
    
    0 讨论(0)
提交回复
热议问题