Sunday 11 October 2015

URLConnection : Get all header fields and values

URLConnection class provides getHeaderFields method, which returns a Map of header field.

public Map<String,List<String>> getHeaderFields()
Returns a map of header fields and respective values.

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 {
    String resource = "https://self-learning-java-tutorial.blogspot.com";

    /* Construct URL object */
    URL url = new URL(resource);

    /* Open URLConnection to this URL */
    URLConnection conn = url.openConnection();

    Map<String, List<String>> headerFields = conn.getHeaderFields();

    Set<String> keys = headerFields.keySet();

    for (String key : keys) {
      List<String> values = headerFields.get(key);
      System.out.print(key + ": ");
      for (String value : values) {
        System.out.print(value + "\t");
      }
      System.out.println();
    }
  }
}

Sample Output

null: HTTP/1.1 200 OK  
Expires: Tue, 19 May 2015 15:17:07 GMT  
X-XSS-Protection: 1; mode=block 
Last-Modified: Mon, 18 May 2015 10:26:27 GMT  
Alternate-Protocol: 80:quic,p=1 
Server: GSE 
X-Content-Type-Options: nosniff 
Cache-Control: private, max-age=0 
Date: Tue, 19 May 2015 15:17:07 GMT 
Vary: Accept-Encoding 
Transfer-Encoding: chunked  
Content-Type: text/html; charset=UTF-8  
Accept-Ranges: none 




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment