Java Reference
In-Depth Information
Example 7-4 reads URLs from the command line and uses these six methods to print
their content type, content length, content encoding, date of last modification, expira‐
tion date, and current date.
Example 7-4. Return the header
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class HeaderViewer {
public static void main ( String [] args ) {
for ( int i = 0 ; i < args . length ; i ++) {
try {
URL u = new URL ( args [ 0 ]);
URLConnection uc = u . openConnection ();
System . out . println ( "Content-type: " + uc . getContentType ());
if ( uc . getContentEncoding () != null ) {
System . out . println ( "Content-encoding: "
+ uc . getContentEncoding ());
}
if ( uc . getDate () != 0 ) {
System . out . println ( "Date: " + new Date ( uc . getDate ()));
}
if ( uc . getLastModified () != 0 ) {
System . out . println ( "Last modified: "
+ new Date ( uc . getLastModified ()));
}
if ( uc . getExpiration () != 0 ) {
System . out . println ( "Expiration date: "
+ new Date ( uc . getExpiration ()));
}
if ( uc . getContentLength () != - 1 ) {
System . out . println ( "Content-length: " + uc . getContentLength ());
}
} catch ( MalformedURLException ex ) {
System . err . println ( args [ i ] + " is not a URL I understand" );
} catch ( IOException ex ) {
System . err . println ( ex );
}
System . out . println ();
}
}
}
Here's the result when used to look at http://www.oreilly.com :
% java HeaderViewer http://www.oreilly.com
Content-type: text/html; charset=utf-8
Date: Fri May 31 18:08:09 EDT 2013
Last modified: Fri May 31 17:04:14 EDT 2013
Search WWH ::




Custom Search