【问题标题】:Android volley - Override Cache Timeout for JSON requestAndroid volley - 覆盖 JSON 请求的缓存超时
【发布时间】:2013-07-06 15:54:08
【问题描述】:

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

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    您可以继承 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?
    • 来自httpheaderparser.parsecacheheaders,如上所述
    • 谢谢。所以我们不需要将服务器响应数据保存在数据库中。这是真的吗?
    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多