Android volley - override cache timeout for JSON request

I am trying to cache JSON requests from the server, however they misuse the Cache-Control header, including (it all ends in the past). I want to redefine it so that calls are cached, say, after 3 hours, regardless of what the server requests. Is it possible? Documentation for Volley - Scarce.

+4
source share
1 answer

You can subclass the JsonObjectRequest class and overwrite parseNetworkResponse. You will notice that calling HttpHeaderParser.parseCacheHeaders is a good place to run:] just wrap this call or replace it and provide your own cache header configuration object [with your clients caching time] in Response.success.

In my implementation, it looks like this:

parseNetworkResponse

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

with forcedClientCaching related members

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

It handles 2 cases:

  • No cache headers.
  • An expired item is displayed in the server cache entry

So, if the server starts sending the correct cache headers with expiration in the future, it will still work.

+12
source

Source: https://habr.com/ru/post/1490431/


All Articles