4

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

但这不起作用。所有请求在网络开启时都能正常工作,但在网络关闭时不会返回缓存数据。请帮忙解决这个问题。

4

3 回答 3

1

用于

File cacheDir = new File(MyApplication.getContext().getCacheDir(), cache);
        myCache= new Cache(cacheDir, cacheSize);

        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(myCache);
于 2016-03-14T15:47:14.117 回答
0

你必须使用Builder

OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache).build();
于 2016-09-30T09:43:40.293 回答
0

您可能还需要在拦截器中重置响应头。

okhttp3.Response originalResponse = chain.proceed(request);
if (NetUtils.hasNetwork(mContext)) {
    //when the network is available, you use the '@Headers' cache time in the interface
    String cacheControl = request.cacheControl().toString();
    int maxAge = 60; // read from cache for 1 minute
    return originalResponse.newBuilder()
            .header("Cache-Control", cacheControl)
            //.header("Cache-Control", "public, max-age=" + maxAge)
            .removeHeader("Progma")
            .build();
} else {
    return originalResponse.newBuilder()
            .header("Cache-Control", "public, only-if-cached, max-stale=2419200") //60 * 60 * 24 * 28 4weeks
            .removeHeader("Pragma")
            .build();
}
于 2016-03-18T09:40:44.560 回答