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.
source share