问题是,如果我将手机置于飞行模式,则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();
}
});
答案 0 :(得分:0)
尝试此代码
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 );
}
};