Home Java Java-get-example Java get Http Headers

Related Tutorials


 
 

Share on Google+Share on Google+

Java get Http Headers

Advertisement
In this section, we are going to illustrate you how to get the Http Headers. Here, we are using the URL class which points the resource.

Java get Http Headers

     

In this section, we are going to illustrate you how to get the Http Headers. Here, we are using the URL class which points the resource. In order to make a communication link between the application and a URL, we have used the class URLConnection.

url.openConnection()-  This method of URL class returns a URLConnection object that represents a connection referred to by the URL.

conn.getHeaderFieldKey(i)-  This method returns the key for the header field.

conn.getHeaderField(i)- This method returns the value for the header field.

Here is the code of GetHttpHeaders.java

import java.net.*;
import java.io.*;

public class GetHttpHeaders{
  public static void main ( String[] args ) throws IOException {
  try 
  {  
  URL url = new URL("http://localhost:8080");
  URLConnection conn = url.openConnection();
  
  for (int i=0; ; i++) 
  {
  String name = conn.getHeaderFieldKey(i);
  String value = conn.getHeaderField(i);
  if (name == null && value == null){
  break
  }
  if (name == null){
  System.out.println("Server HTTP version, Response code:");
  System.out.println(value);
  System.out.print("\n");
  }
  else{
  System.out.println(name + "=" + value);
  }
  }
  
  catch (Exception e) {}
  }
}

To run the above example, first of all start the tomcat as you have taken the resource http://localhost:8080. Then compile the class and execute the example, you will get the Http Headers on the console.

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 1, 2008

Related Tutorials

Discuss: Java get Http Headers  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com