Here is my code:
final HttpURLConnection conn = (HttpURLConnection) sourceURL.openConnection();
if (cachedPage != null) {
if (cachedPage.eTag != null) {
conn.setRequestProperty("If-None-Match", cachedPage.eTag);
}
conn.setIfModifiedSince(cachedPage.pageLastModified);
}
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
newCachedPage.eTag = conn.getHeaderField("ETag");
newCachedPage.pageLastModified = conn.getHeaderFieldDate("Last-Modified", 0);
} else if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
// Never reaches here
}
I never seem to get the HTTP_NOT_MODIFIED response code, even hitting the same server several times in quick succession – where there is definitely no change to the page. Also, conn.getHeaderField(“ETag”) always seems to respond null, and sometimes conn.getHeaderFieldDate(“Last-Modified”, 0) returns 0. I’ve tried this against a variety of web servers.
Can anyone tell me what I’m doing wrong?
You’re all dependent on the server config.
If you get an
Expiresresponse header, then it just means that you don’t need to request anything until the specified expire time. If you get aLast-Modifiedresponse header, then it means that you should be able to useIf-Modified-Sinceto test it. If you get anETagresponse header, then it means that you should be able to useIf-None-Matchto test it.Lets take http://cdn3.sstatic.net/stackoverflow/img/favicon.ico as an example (the Stackoverflow’s favicon image):
This gives:
Now, do a
If-Modified-Sincewith the same value asLast-Modified:This gives as expected a 304:
Now, do a
If-None-Matchwith the same value asETag:This gives unexpectedly a 200:
Even more surprising, when the both headers are set with random garbage value as
ETag, the server still gives a 304. This is an indication that theIf-None-Matchis completely ignored by the server behind http://cdn3.sstatic.net. That might be a (proxy) configuration issue or be done fully awarely (not for obvious reasons imho).