我已经阅读了很多关于我的问题的问题和答案,但我无法理解如何解决它。
我需要从服务器获取响应并将其存储在缓存中。在此之后,当设备处于脱机状态时,我想使用缓存响应。当设备在线时,我想从服务器获取响应。
看起来并不那么复杂。
以下是我尝试这样做的方式(代码示例):
1)创建缓存的方法
Cache provideOkHttpCache() {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(this.getCacheDir(), cacheSize);
return cache;
}
2)创建一个Interceptor来修改缓存控制头
Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
CacheControl.Builder cacheBuilder = new CacheControl.Builder();
cacheBuilder.maxAge(0, TimeUnit.SECONDS);
cacheBuilder.maxStale(365, TimeUnit.DAYS);
CacheControl cacheControl = cacheBuilder.build();
Request request = chain.request();
if (isOnline()) {
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}
okhttp3.Response originalResponse = chain.proceed(request);
if (isOnline()) {
int maxAge = 20; // read from cache
okhttp3.Response response = originalResponse.newBuilder()
.header("cache-control", "public, max-age=" + maxAge)
.build();
return response;
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
okhttp3.Response response = originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
return response;
}
}
};
3)创建OkHttpClient和Retrofit
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(provideOkHttpCache())
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://randomuser.me/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
4)进行网络呼叫的方法
private void networkCall() {
Log.v(TAG, "networkCall() is called");
Call<RandomUsers> randomUsersCall = getRandomUserService().getRandomUsers(10);
randomUsersCall.enqueue(new Callback<RandomUsers>() {
@Override
public void onResponse(Call<RandomUsers> call, @NonNull Response<RandomUsers> response) {
if (response.isSuccessful()) {
try {
Log.v(TAG, "headers = " + response.headers());
} catch (Exception e) {
e.printStackTrace();
}
mAdapter = new RandomUserAdapter();
mAdapter.setItems(response.body().getResults());
recyclerView.setAdapter(mAdapter);
} else if (response.code() == 504) {
Log.v(TAG, "response body = " + response.raw().cacheResponse());
}
}
@Override
public void onFailure(Call<RandomUsers> call, Throwable t) {
Log.v("cache-control", "response failure");
}
});
}
所以,这是问题所在: 该应用程序永远不会进入第2页中的脱机代码块。 如果max-age仍然是合法的,则使用缓存响应进行改造。 如果反应在前一段时间被缓存,并且max-age不合法,则有两种情况:
1)设备在线:Retrofit
向服务器发出新请求(一切正常)
2)设备离线:调用onFailure
内的回调方法networkCall()
(第4页代码示例)
我的代码有什么问题?我真的不明白为什么应用程序无法使用脱机控制的离线情况。
抱歉文字过多。 谢谢!
答案 0 :(得分:4)
解决。
诀窍是合并Interceptor
和NetworkInterceptor
。
步骤:
1)为两个拦截器分别使用REWRITE_CACHE_CONTROL_INTERCEPTOR,一个用于在线工作,另一个用于离线工作:
Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isOnline()) {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
request = request.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return chain.proceed(request);
}
};
Interceptor ONLINE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
int maxAge = 60; // read from cache
return response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
}
};
2)将拦截器添加到okHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(OFFLINE_INTERCEPTOR)
.addNetworkInterceptor(ONLINE_INTERCEPTOR)
.cache(provideOkHttpCache())
.build();