使用Okhttp3.0和retrofit2

时间:2016-10-31 12:09:03

标签: android caching retrofit2 okhttp3 okhttp

我正在使用Retrofit2& OKHTTP3 for REST API&在我的Android应用程序中。我的要求是我必须缓存在离线模式下使用应用程序的请求。事情是我能够缓存请求。但是当用户再次上线时,应该从后端新获取数据,它不应该提供缓存的响应。我怎样才能做到这一点。下面是我的网络拦截器

网络拦截器

public class CachingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();


            if (Util.isOnline()) {
                request = request.newBuilder()
                        .header("Cache-Control", "only-if-cached")
                        .build();
            } else {
                request = request.newBuilder()
                        .header("Cache-Control", "public, max-stale=2419200")
                        .build();
            }

        Response response= chain.proceed(request);
        return response.newBuilder()
                .header("Cache-Control", "max-age=86400")
                .build();
    }
}

2 个答案:

答案 0 :(得分:0)

参考此回答link OkHttp Interceptor是离线时访问缓存的正确方法:

答案 1 :(得分:0)

知道了。如果设备处于离线状态,我将缓存控制标头设置为“public,only-if-cached,max-stale = 86400”(这将设置陈旧时间到1天)。现在,如果设备在线,它将从服务器上新获取。

OkHttpClient

okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new OfflineCachingInterceptor())
            .cache(cache)
            .build();

OfflineCachingInterceptor

public class OfflineCachingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        //Checking if the device is online
        if (!(Util.isOnline())) {
            // 1 day stale
            int maxStale = 86400;
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
}