Java Reference
In-Depth Information
Connection: close
If-Modified-Since: Fri, 31 Oct 2014 19:22:07 GMT
If the document has changed since that time, the server will send it as usual. Otherwise,
it replies with a 304 Not Modified message, like this:
HTTP/1.0 304 Not Modified
Server: WN/1.15.1
Date: Sun, 02 Nov 2014 16:26:16 GMT
Last-modified: Fri, 29 Oct 2004 23:40:06 GMT
The client then loads the document from its cache. Not all web servers respect the If-
Modified-Since field. Some will send the document whether it's changed or not.
The ifModifiedSince field in the URLConnection class specifies the date (in millisec‐
onds since midnight, Greenwich Mean Time, January 1, 1970), which will be placed in
the If-Modified-Since header field. Because ifModifiedSince is protected , programs
should call the getIfModifiedSince() and setIfModifiedSince() methods to read
or modify it:
public long getIfModifiedSince ()
public void setIfModifiedSince ( long ifModifiedSince )
Example 7-13 prints the default value of ifModifiedSince , sets its value to 24 hours
ago, and prints the new value. It then downloads and displays the document—but only
if it's been modified in the last 24 hours.
Example 7-13. Set ifModifiedSince to 24 hours prior to now
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class Last24 {
public static void main ( String [] args ) {
// Initialize a Date object with the current date and time
Date today = new Date ();
long millisecondsPerDay = 24 * 60 * 60 * 1000 ;
for ( int i = 0 ; i < args . length ; i ++) {
try {
URL u = new URL ( args [ i ]);
URLConnection uc = u . openConnection ();
System . out . println ( "Original if modified since: "
+ new Date ( uc . getIfModifiedSince ()));
uc . setIfModifiedSince (( new Date ( today . getTime ()
- millisecondsPerDay )). getTime ());
System . out . println ( "Will retrieve file if it's modified since "
+ new Date ( uc . getIfModifiedSince ()));
try ( InputStream in = new BufferedInputStream ( uc . getInputStream ())) {
Search WWH ::




Custom Search