Sunday, March 27, 2016

Java Networking Examples : How To Get HTTP Header Information of URL

Intro

This examples will demonstrates how to get header information of URL such as status code, response code, content type, and etc.

To get a header information of URL, you can use HttpURLConnection.getHeaderFields() method.

Examples


package com.freesamplecode.java.networking;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class GetHeaderInformationURLDemo {
 public static void main(String[] args){
  
  try {
   //create URL object
   URL url = new URL("http://free-samplecode.blogspot.com/p/java.html");
   
   //open URL connection
   HttpURLConnection httpUrlConnection =  (HttpURLConnection) url.openConnection();
   
   //get all URL header informations
   Map headerField = httpUrlConnection.getHeaderFields();
   
   Set set = headerField.entrySet();
   
   Iterator it = set.iterator();
   
   while(it.hasNext()){
    System.out.println(it.next());
   }
   

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Output


null=[HTTP/1.1 200 OK]
Expires=[Sun, 27 Mar 2016 13:31:17 GMT]
X-XSS-Protection=[1; mode=block]
Last-Modified=[Sun, 27 Mar 2016 13:15:17 GMT]
Connection=[Keep-Alive]
Server=[GSE]
X-Content-Type-Options=[nosniff]
Cache-Control=[private, max-age=0]
Date=[Sun, 27 Mar 2016 13:31:17 GMT]
Vary=[Accept-Encoding]
Transfer-Encoding=[chunked]
Content-Type=[text/html; charset=UTF-8]
Accept-Ranges=[none]

Screenshot

How To Get HTTP Header Information of URL In Java

Related Posts:

0 comments: