OkHttpClient离线缓存

时间:2015-09-16 12:43:05

标签: caching offline okhttp

我尝试使用OkHttpClient实现响应缓存,但我有点困惑。要做到这一点,我就是这样使用Interceptor:

final Interceptor interceptor = chain -> {
    Response response = chain.proceed(chain.request());
    if (isOnline()) {
        int maxAge = 60; // read from cache for 1 minute
        response = response.newBuilder()
                .addHeader("Cache-Control", "public, max-age=" + maxAge)
                .build();
    } else {
        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
        response = response.newBuilder()
                .addHeader("Cache-Control","public, only-if-cached, max-stale=" + maxStale)
                .build();
    }
    if (!response.isSuccessful()) {
        response = response.cacheResponse();
    }
    return response;
}
mClient.networkInterceptors().add(interceptor);
mClient.interceptors().add(interceptor);

但如果没有互联网连接,我会收到UnknownHostException。但我希望得到缓存的响应。怎么处理呢?

0 个答案:

没有答案