我在网络请求中使用 retrofit_2 (beta4) 和 okhttp_3 库。当网络关闭并且应用程序必须显示上一个相同请求的响应数据时,我需要缓存响应数据。我发现的所有解决此问题的指南都使用 okhttp lib(不是 okhttp_3)。我试图解决问题:
public class ApiFactory {
private static final int CONNECT_TIMEOUT = 45;
private static final int WRITE_TIMEOUT = 45;
private static final int READ_TIMEOUT = 45;
private static final long CACHE_SIZE = 10 * 1024 * 1024; // 10 MB
private static OkHttpClient.Builder clientBuilder;
static {
clientBuilder = new OkHttpClient
.Builder()
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.cache(new Cache(MyApp.getInstance().getCacheDir(), CACHE_SIZE)) // 10 MB
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (MyApp.getInstance().isNetwConn()) {
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);
}
});
}
@NonNull
public static ApiRequestService getApiRequestService() {
return getRetrofitDefault().create(ApiRequestService.class);
}
@NonNull
private static Retrofit getRetrofitDefault() {
return new Retrofit.Builder()
.baseUrl(NetworkUrls.URL_MAIN)
.addConverterFactory(GsonConverterFactory.create())
.callbackExecutor(Executors.newFixedThreadPool(5))
.callbackExecutor(Executors.newCachedThreadPool())
.callbackExecutor(new Executor() {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
mHandler.post(command);
}
})
.client(clientBuilder.build())
.build();
}
}
但这不起作用。所有请求在网络开启时都能正常工作,但在网络关闭时不会返回缓存数据。请帮忙解决这个问题。