Java Reference
In-Depth Information
Do not assume the value returned by getHeaderField() is valid. You must check to
make sure it is nonnull.
public String getHeaderFieldKey(int n)
This method returns the key (i.e., the field name) of the n th header field (e.g., Content-
length or Server ). The request method is header zero and has a null key. The first
header is one. For example, in order to get the sixth key of the header of the URLConnec
tion uc , you would write:
String header6 = uc . getHeaderFieldKey ( 6 );
public String getHeaderField(int n)
This method returns the value of the n th header field. In HTTP, the starter line containing
the request method and path is header field zero and the first actual header is one.
Example 7-5 uses this method in conjunction with getHeaderFieldKey() to print the
entire HTTP header.
Example 7-5. Print the entire HTTP header
import java.io.* ;
import java.net.* ;
public class AllHeaders {
public static void main ( String [] args ) {
for ( int i = 0 ; i < args . length ; i ++) {
try {
URL u = new URL ( args [ i ]);
URLConnection uc = u . openConnection ();
for ( int j = 1 ; ; j ++) {
String header = uc . getHeaderField ( j );
if ( header == null ) break ;
System . out . println ( uc . getHeaderFieldKey ( j ) + ": " + header );
}
} catch ( MalformedURLException ex ) {
System . err . println ( args [ i ] + " is not a URL I understand." );
} catch ( IOException ex ) {
System . err . println ( ex );
}
System . out . println ();
}
}
}
For example, here's the output when this program is run against http://www.oreilly.com :
% java AllHeaders http://www.oreilly.com
Date: Sat, 04 May 2013 11:28:26 GMT
Server: Apache
Last-Modified: Sat, 04 May 2013 07:35:04 GMT
Search WWH ::




Custom Search