[英]Retrofit Offline cashing returns a null response.body()
我嘗試了此鏈接,並使用此鏈接構建了脫機的Retrofit緩存。
問題是,如果我將手機置於飛行模式,則Response.body()始終為null。
這是我的代碼:
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();
}
});
試試這個代碼
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 );
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.