Get and display http header information for a URL connection in Java

Description

The following code shows how to get and display http header information for a URL connection.

Example


//from   w  ww. j a va  2s  .  c o m
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {

  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com/");
    URLConnection urlConnection = url.openConnection();
    Map<String, List<String>> headers = urlConnection.getHeaderFields();
    
    Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();
    for (Map.Entry<String, List<String>> entry : entrySet) {
      String headerName = entry.getKey();
      System.out.println("Header Name:" + headerName);
      List<String> headerValues = entry.getValue();
      for (String value : headerValues) {
        System.out.print("Header value:" + value);
      }
      System.out.println();
      System.out.println();
    }

  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode