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);
点赞