我在网络请求中使用了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();
}
}
但这不起作用.当网络处于开启状态时,所有请求都能正常工作,但在网络关闭时不能返回缓存数据.请帮助解决这个问题.
解决方法:
用于
File cacheDir = new File(MyApplication.getContext().getCacheDir(), cache);
myCache= new Cache(cacheDir, cacheSize);
okHttpClient = new OkHttpClient();
okHttpClient.setCache(myCache);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。