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

4

我想要缓存从服务器请求的JSON数据,但是它们错误地使用了Cache-Control头文件以及其他一些(所有内容都已过期)。我希望覆盖它,使调用被缓存,例如,3小时,而不管服务器请求什么。这可能吗?Volley的文档很少。

1个回答

12

你可以继承 JsonObjectRequest 类并覆盖 parseNetworkResponse 方法。你会注意到调用了 HttpHeaderParser.parseCacheHeaders - 这是一个很好的起点:]只需包装此调用或替换它并提供自己的虚拟缓存头配置对象(带有您专有的客户端缓存时间)给 Response.success

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

parseNetworkResponse

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;
}

它处理以下两种情况:

  • 没有设置缓存头部信息
  • 服务器缓存项指示过期的内容

所以,如果服务器开始发送带有将来到期时间的正确缓存头部信息,它仍然可以工作。


抱歉,你从哪里获取Cache.Entry的? - StackOverflowed
从 httpheaderparser.parsecacheheaders,如上所述 - Makibo
谢谢。所以我们不需要将服务器响应数据保存在数据库中。这是真的吗? - DolDurma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接