Sunday, 3 September 2017

Get headers from url using HttpURLConnection

Below step by step procedure explains, how to get all headers from http url.

Step 1: Get HttpURLConnection instance from url.
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
                 return httpUrlConnection;
                
Step 2: Use 'getHeaderFields' method of HttpURLConnection instance to get all the headers.
                 Map<String, List<String>> headers = httpURLConnection.getHeaderFields();

                 for (String headerName : headers.keySet()) {
                          System.out.println(headerName + " : " + headers.get(headerName));
                 }
                
Find below working application.

Test.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class Test {

 private static HttpURLConnection getURLConnection(String urlToConnect) throws IOException {
  URL url = new URL(urlToConnect);
  HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
  return httpUrlConnection;
 }

 private static void printHeaders(HttpURLConnection httpURLConnection) {
  Map<String, List<String>> headers = httpURLConnection.getHeaderFields();

  for (String headerName : headers.keySet()) {
   System.out.println(headerName + " : " + headers.get(headerName));
  }
 }

 public static void main(String[] args) throws IOException {
  String url = "https://self-learning-java-tutorial.blogspot.com/2016/05/java-home-page.html";
  HttpURLConnection httpUrlConnection = getURLConnection(url);
  printHeaders(httpUrlConnection);

 }

}


Output
Transfer-Encoding : [chunked]
null : [HTTP/1.1 200 OK]
Alt-Svc : [quic=":443"; ma=2592000; v="39,38,37,35"]
Server : [GSE]
X-Content-Type-Options : [nosniff]
Last-Modified : [Thu, 31 Aug 2017 17:49:01 GMT]
Date : [Fri, 01 Sep 2017 09:50:33 GMT]
Accept-Ranges : [none]
Cache-Control : [private, max-age=0]
Vary : [Accept-Encoding]
Expires : [Fri, 01 Sep 2017 09:50:33 GMT]
X-XSS-Protection : [1; mode=block]
Content-Type : [text/html; charset=UTF-8]



Previous                                                 Next                                                 Home

No comments:

Post a Comment