Getting the HTTP headers from an URL



Introduction

In an other article we already read from the URL. In this example only the HTTP headers are read using the same URL object:

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) {
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.