How can I retrieve the HTTP header information for a URL?

Tim Rohaly

To examine the HTTP headers, you use the getHeaderField() method of URLConnection. The HTTP headers are returned separately from the content of the URL, and reading from the URL's input stream only allows you to access the content. The simple program below prints out all the headers for a URL specified as the first command-line argument:

import java.net.*;

public class PrintHeaders {

    public static void main(String[] args) throws Exception {
        URL url = new URL(args[0]);
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        String header = connection.getHeaderField(0);
        System.out.println(header);
        System.out.println("---Start of headers---");
        int i = 1;
        while ((header = connection.getHeaderField(i)) != null) {
            String key = connection.getHeaderFieldKey(i);
            System.out.println(((key==null) ? "" : key + ": ") + header);
            i++;
        }
        System.out.println("---End of headers---");
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact