android - 当服务器关闭且没有响应时如何使用改造缓存?
问题描述
我正在使用改造从服务器获取数据,我启用了缓存系统并且它工作正常,但只有当用户离线时。当服务器没有响应时,我想使用改造缓存。
谁能告诉我该怎么做?
我正在使用这些拦截器并将它们添加到我的客户端。
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();
}
解决方案
推荐阅读
- javascript - 将变量传递到 document.getElementById() - Javascript
- json - laravel 按数据字段为用户选择通知
- chapel - 各种计算的性能图
- smartcontracts - 如何设置每天/每周/每月支付的合同..从发送方到接收方的 XAS?
- javascript - 使用 AJAX 将数据发布到 Google 表单
- swift - 包括特殊字符的 Swift 字符串
- entity-framework-core - 无法使用 Entity Framework Core 2.1 更新子实体
- c++ - 静态分配的纯虚拟父类引用对静态分配的子类对象是否合法?
- reactjs - react-data-grid:可排序的列标题。什么决定了排序图标呈现在文本的哪一侧?
- microsoft-graph-api - 更新共享联系人时出错