How to get HTTP Response Header using URLConnection in Java

  • 05 May 2017
  • ADM

 

How to get HTTP Response Header using URLConnection in Java - images/logos/java.jpg

 

Here is a simple example how to get HTTP Response Header using URLConnection in Java.

Example

package com.admfactory.http;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HTTPHeaderExample {
    public static void main(String[] args) {

	try {
	    System.out.println("Get HTTP Headers Example");
	    System.out.println();

	    URL obj = new URL("https://www.google.com");
	    URLConnection conn = obj.openConnection();

	    System.out.println("List all headers:");
	    Map<String, List<String>> map = conn.getHeaderFields();

	    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
		System.out.println(entry.getKey() + ": " + entry.getValue());
	    }
	    System.out.println();
	    System.out.println("Get Header by key:");
	    String server = conn.getHeaderField("Content-Type");

	    if (server == null) {
		System.out.println("Key 'Content-Type' is not found!");
	    } else {
		System.out.println("Content-Type: " + server);
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	}

    }
}

Output

Get HTTP Headers Example

List all headers:
Transfer-Encoding: [chunked]
null: [HTTP/1.1 200 OK]
Alt-Svc: [quic=":443"; ma=2592000; v="37,36,35"]
Server: [gws]
P3P: [CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."]
Date: [Fri, 05 May 2017 15:45:43 GMT]
Accept-Ranges: [none]
X-Frame-Options: [SAMEORIGIN]
Cache-Control: [private, max-age=0]
Vary: [Accept-Encoding]
Set-Cookie: [NID=102=SzMiPmg23g5Gbl6ky752KYkMtIQ36ued0fGFreQlRm7hWQOOzQo2u_8hnou0xPIYufnzEKtwTgG7_UlY9MSu3cwL77FjkiM2ZN26MijiC391xycU5FqCwEqmL1_DbIhV; expires=Sat, 04-Nov-2017 15:45:43 GMT; path=/; domain=.google.ro; HttpOnly]
Expires: [-1]
X-XSS-Protection: [1; mode=block]
Content-Type: [text/html; charset=ISO-8859-2]

Get Header by key:
Content-Type: text/html; charset=ISO-8859-2

 

References