Android HttpsURLConnection, how to tell if the response is cached?

1.1k Views Asked by At

I've got an app targeting ICS and above, and I'm trying to use HttpsURLConnection and HttpResponseCache to cache a web service response. It makes the request with an etag, and the server will return 304 if not modified. It appears to be returning stuff from the cache, however, I'm not receiving any indication that the response is from cache. The response code I'm getting from connection.getResponseCode() is 200, not 304. I need to know if it's cached because I want to know if it's changed so I can mark it as read (it's a fairly long string, and I would not like to have to compare the two). Is there something I can set or something I can check so I know that it is from the cache instead of freshly fetched?

2

There are 2 best solutions below

1
On

You can try using the response header information. Compare the dates, if you are getting the same date for the same request, then it's the cache.

HttpURLConnection conn;
conn = (HttpURLConnection)url.openConnection();
...
conn.connect();

System.out.println(conn.getHeaderField("Date"));

if you want to print the whole header:

Map headerfields = conn.getHeaderFields();
Set headers = headerfields.entrySet(); 
for(Iterator i = headers.iterator(); i.hasNext();){ 
    Map.Entry map = (Map.Entry)i.next();
    System.out.println(map.getKey() + " : " + map.getValue() + "");
}
0
On

After print the whole response header on Android 9. I found the following fields useful.

HttpURLConnection conn;

...
conn.getHeaderField("X-Android-Response-Source"); // "NETWORK 200" or "CACHE 200"

conn.getHeaderField("Warning"); // null or "110 HttpURLConnection "Response is stale""

It should have other status messages that I have not tested.