android – 使用retrofit2 okhttp3缓存响应数据

我在网络请求中使用了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);

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...