首页 > 解决方案 > 当服务器关闭且没有响应时如何使用改造缓存?

问题描述

我正在使用改造从服务器获取数据,我启用了缓存系统并且它工作正常,但只有当用户离线时。当服务器没有响应时,我想使用改造缓存。

谁能告诉我该怎么做?

我正在使用这些拦截器并将它们添加到我的客户端。

static Interceptor onlineInterceptor = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response response = chain.proceed(chain.request());
        int maxAge = 60; // read from cache for 60 seconds even if there is internet connection
        return response.newBuilder()
                .header("Cache-Control", "public, max-age=" + maxAge)
                .removeHeader("Pragma")
                .build();
    }
};

static Interceptor offlineInterceptor = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!isInternetAvailable()) {
            int maxStale = 60 * 60 * 24 * 30; // offline cache available for 30 days
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .removeHeader("Pragma")
                    .build();
        }
        return chain.proceed(request);
    }
};

public static boolean isInternetAvailable() {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

标签: androidcachingretrofit2okhttp

解决方案


推荐阅读