【问题标题】:volley - json caching is not working properlyvolley - json 缓存无法正常工作
【发布时间】:2014-04-14 23:16:01
【问题描述】:

服务器向我发送 json 对象、过期和 ETAg .. 我想 Voley 将此对象保存在缓存中,并在下一次对该对象的请求中使用对服务器的请求,包括标头中的 ETag。如果响应为 304 Not Modified,则应使用缓存资源,如果为 200 OK,则应使用来自服务器的新资源。

Volley 根本不发送请求(如果缓存未过期),或者如果它已过期,它会发送带有 If-None-Match + etag 字符串的新请求。服务器总是以 200 响应

【问题讨论】:

    标签: android caching android-volley


    【解决方案1】:

    如果 Volley 检测到缓存条目尚未过期,它根本不会向服务器发出请求。以下是一些代码摘录来证明这一点:

    // If it is completely expired, just send it to the network.
    if (entry.isExpired()) {
        request.addMarker("cache-hit-expired");
        request.setCacheEntry(entry);
        mNetworkQueue.put(request);
        continue;
    }
    

    还有:

    if (!entry.refreshNeeded()) {
        // Completely unexpired cache hit. Just deliver the response.
        mDelivery.postResponse(request, response);
    } else {
        // Soft-expired cache hit. We can deliver the cached response,
        // but we need to also send the request to the network for
        // refreshing.
        request.addMarker("cache-hit-refresh-needed");
        request.setCacheEntry(entry);
    
        // Mark the response as intermediate.
        response.intermediate = true;
    
        // Post the intermediate response back to the user and have
        // the delivery then forward the request along to the network.
        mDelivery.postResponse(request, response, new Runnable() {
            @Override
            public void run() {
                try {
                    mNetworkQueue.put(request);
                } catch (InterruptedException e) {
                    // Not much we can do about this.
                }
            }
        });
    }
    

    您可能希望通过将max-age 设置为Cache-ControlExpires 标头来控制服务器上的资源过期,以便调整客户端的缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2019-09-01
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多