How can I retrieve the HTTP header information for a URL?
Created May 4, 2012
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---"); } }