The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.net  [27 examples] > HTTP  [4 examples]

e140. Getting the Response Headers from an HTTP Connection

    try {
        // Create a URLConnection object for a URL
        URL url = new URL("http://hostname:80");
        URLConnection conn = url.openConnection();
    
        // List all the response headers from the server.
        // Note: The first call to getHeaderFieldKey() will implicit send
        // the HTTP request to the server.
        for (int i=0; ; i++) {
            String headerName = conn.getHeaderFieldKey(i);
            String headerValue = conn.getHeaderField(i);
    
            if (headerName == null && headerValue == null) {
                // No more headers
                break;
            }
            if (headerName == null) {
                // The header value contains the server's HTTP version
            }
        }
    } catch (Exception e) {
    }
Here's a sample of headers from a website:
    Key=Value
    
    null=HTTP/1.1 200 OK
    Server=Netscape-Enterprise/4.1
    Date=Mon, 11 Feb 2002 09:23:26 GMT
    Cache-control=public
    Content-type=text/html
    Etag="9fa67d2a-58-71-3bbdad3283"
    Last-modified=Fri, 05 Oct 2001 12:53:06 GMT
    Content-length=115
    Accept-ranges=bytes
    Connection=close

 Related Examples
e141. Getting the Cookies from an HTTP Connection
e142. Sending a Cookie to an HTTP Server
e143. Preventing Automatic Redirects in a HTTP Connection

See also: Datagram    Encodings    Hostnames and IP Addresses    Multicast    Sockets    URLs   


© 2002 Addison-Wesley.