Android volley - 覆盖 JSON 请求的缓存超时

标签 android android-volley

我正在尝试缓存来自服务器的 JSON 请求,但是,它们错误地使用了 Cache-Control header ,等等(一切都在过去过期)。我想覆盖它,以便将调用缓存 3 小时,而不管服务器请求什么。那可能吗? Volley 的文档很少。

最佳答案

您可以子类化 JsonObjectRequest 类并覆盖 parseNetworkResponse。您会注意到对 HttpHeaderParser.parseCacheHeaders 的调用 - 这是一个很好的起点 :] 只需包装此调用或替换它并提供您自己的虚拟缓存 header 配置对象 [具有您专有的客户端缓存时间] 到 Response.success。

在我的实现中它看起来像这样:

解析网络响应

return Response.success(payload, enforceClientCaching(HttpHeaderParser.parseCacheHeaders(response), response));

enforceClientCaching相关的成员正在

protected static final int defaultClientCacheExpiry = 1000 * 60 * 60; // milliseconds; = 1 hour

protected Cache.Entry enforceClientCaching(Cache.Entry entry, NetworkResponse response) {
    if (getClientCacheExpiry() == null) return entry;

    long now = System.currentTimeMillis();

    if (entry == null) {
        entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = response.headers.get("ETag");
        entry.softTtl = now + getClientCacheExpiry();
        entry.ttl = entry.softTtl;
        entry.serverDate = now;
        entry.responseHeaders = response.headers;
    } else if (entry.isExpired()) {
        entry.softTtl = now + getClientCacheExpiry();
        entry.ttl = entry.softTtl;
    }

    return entry;
}

protected Integer getClientCacheExpiry() {
    return defaultClientCacheExpiry;
}

它处理两种情况:

  • 没有设置缓存 header
  • 服务器缓存条目指示过期项

因此,如果服务器在未来开始发送正确的缓存 header ,它仍然可以工作。

关于Android volley - 覆盖 JSON 请求的缓存超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541498/

相关文章:

android - popUpTo 似乎在导航组件中不起作用

java - 如何在循环中发出 Volley 请求,直到出现特定响应

android - 如何在android中获取访问 token paypal

android - 在 Volley 请求中使用 UTF-8 编码失败

java - Android:用户能够导入文件的存储选项方法

android - 如何获取 Battery Historian 在 csv 中计算的错误报告数据

android - 删除带有 header 和参数的请求 Volley

java - 如何使用 Volley 获取错误消息描述

安卓错误: dalvik. system.BaseDexClassLoader.findClass

android - 组织.json.JSONException : Unterminated object at character on Android