Protected by Copyscape
Powered By Blogger

Saturday, January 11, 2020

How to extract the headers of any HTTP request using HttpURLConnection?

As I earlier mentioned in my post where I showed, how we can validate all the links on a webpage using HttpURLConnection? My main intention is you to clearly understand that what objectives we can achieve with HttpURLConnection class which is a subclass of URLConnection class.

The below code which I have written it will help to extract the header information, status code, response code and status line.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HTTPURLConnect
{
public static URL url;
public static HttpURLConnection huc;

public static void main(String args[])
{
try
{
url = new URL("http://www.google.com");
huc = (HttpURLConnection)url.openConnection();
System.out.println(huc.getHeaderFields());
for(int i=1;i<=10;i++)
{
System.out.println(huc.getHeaderFieldKey(i)+"  :"+huc.getHeaderField(i));
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}


}
}

Now understand the code 

First I have created an object of URL and HttpURLConnection class.
        public static URL url;
public static HttpURLConnection huc;

To support the above 2 lines I have imported below 2 packages in my code.
        import java.net.HttpURLConnection;
        import java.net.URL;

In main method I have initialized the below URL class. URL stands for Uniform Resource Locator a pointer to a "resource" on World Wide Web(www).
       URL url=new URL("http://www.google.com");

Now, we have to type cast the url object to HttpURLConnection class.
       huc=(HttpURLConnection)url.openConnection();

Now printing all the header fields using below line
       System.out.println(huc.getHeaderFieldKey(i)+"  :"+huc.getHeaderField(i));

Output:
Date  :Sat, 11 Jan 2020 03:34:40 GMT
Expires  :-1
Cache-Control  :private, max-age=0
Content-Type  :text/html; charset=ISO-8859-1
P3P  :CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server  :gws
X-XSS-Protection  :0

X-Frame-Options  :SAMEORIGIN



If you come across any doubts or question on this then please write the same in comment box and i will try to revert at the earliest.

Best of luck!


No comments: