Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

608 Part II: The Java Library


String getHeaderField(intidx) Returns the value of the header field at indexidx.
(Header field indexes begin at 0.) Returns null if the
value ofidxexceeds the number of fields.
String getHeaderField(StringfieldName) Returns the value of header field whose name is
specified byfieldName. Returns null if the specified
name is not found.
String getHeaderFieldKey(intidx) Returns the header field key at indexidx. (Header
field indexes begin at 0.) Returns null if the value
ofidxexceeds the number of fields.
Map<String, List<String>>
getHeaderFields( )

Returns a map that contains all of the header fields
and values.
long getLastModified( ) Returns the time and date, represented in terms
of milliseconds since Januar y 1, 1970 GMT, of the
last modification of the resource. Zero is returned
if the last-modified date is unavailable.
InputStream getInputStream( )
throws IOException

Returns anInputStreamthat is linked to the
resource. This stream can be used to obtain
the content of the resource.

Notice thatURLConnectiondefines several methods that handle header information. A
header consists of pairs of keys and values represented as strings. By usinggetHeaderField( ),
you can obtain the value associated with a header key. By callinggetHeaderFields( ), you
can obtain a map that contains all of the headers. Several standard header fields are available
directly through methods such asgetDate( )andgetContentType( ).
The following example creates aURLConnectionusing theopenConnection( )method
of aURLobject and then uses it to examine the document’s properties and content:

// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;

class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();

// get date
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));

// get content type
System.out.println("Content-Type: " + hpCon.getContentType());
Free download pdf