Friday, August 28, 2009

Retrieve HTTP Header information using Java

HttpURLConnection java class is used to retrieve HTTP Header Information. HttpURLConnection class provides connect() and disconnect() method in order to connect to url or disconnect.

You can check that whether connection to URL is successfull or not by checking response Code. if response code if 200 and Response message is OK then connection is successfull.

HttpURLConnection provides two useful method called getHeaderField() and getHeaderFieldKey(). Using these methods you can get key and value of HTTP Header and can retrieve HTTP Header information.Please have a look at below java program which retrieves http header information.

Java Program to Retrieve Header Information: 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anuj.network;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * @author Anuj Patel
 */
public class RetrieveHTTPHeaderInfo {
    public static void main(String[] args) {
        
        // Proxy Server Address
 /*System.getProperties().put("http.proxyHost", "PROXY_SERVER"); 
        System.getProperties().put("http.proxyPort", "PROXY_PORT");*/

        try {
            URL url = new URL("http://www.google.com");
            
            HttpURLConnection httpurlcon = (HttpURLConnection)(url.openConnection());
            httpurlcon.setAllowUserInteraction(false);
            httpurlcon.setDoInput(true);
            httpurlcon.setDoOutput(false);
            httpurlcon.setUseCaches(false);

            //connect to http URL
            httpurlcon.connect();

            //Display Basic HTTP Header Information
            System.out.println("Content Type - " + httpurlcon.getContentType());
            System.out.println("Response Code - " + httpurlcon.getResponseCode());
            System.out.println("Response Message - " + httpurlcon.getResponseMessage());
            System.out.println("Content length - " + httpurlcon.getContentLength());
            
            //Display Header Information
            String header = httpurlcon.getHeaderField(0);
            System.out.println(header);
            System.out.println("--Header information---");
            int i = 1;
            while ((header = httpurlcon.getHeaderField(i)) != null) {
                String key = httpurlcon.getHeaderFieldKey(i);
                System.out.println(((key == null) ? "" : key + ": ") + header);
                i++;
            }

            System.out.println("--- Reading from Stream and Writing to Stream ---");
            BufferedInputStream in = new BufferedInputStream(httpurlcon.getInputStream(), 4096);
            BufferedOutputStream out = new BufferedOutputStream(System.out, 4096);
            try {
                while (in.available() > 0) {
                    out.write(in.read());
                }
            } catch (Exception e) {
                System.out.println(e);
            }                

            //close IO
            out.close();
            in.close();
            
            //Disconnect httpURL Connection
            httpurlcon.disconnect();
            
        } catch (IOException e) {
            System.out.println(e);
        }

        System.exit(0);
    }
}

Output :
 Content Type - text/html; charset=ISO-8859-1

Response Code - 200

Response Message - OK

Content length - -1

HTTP/1.1 200 OK

--Header information---

Date: Sat, 25 Aug 2012 15:06:54 GMT

Expires: -1

Cache-Control: private, max-age=0

Content-Type: text/html; charset=ISO-8859-1

Set-Cookie: PREF=ID=2ef70139b59ecad9:FF=0:TM=1345907214:LM=1345907214:S=SAX3vxDwUAf4knOQ; expires=Mon, 25-Aug-2014 15:06:54 GMT; path=/; domain=.google.co.in

Set-Cookie: NID=63=hYntFZeseVtreoCRbn3i4TIA6HhuipPrtQnV8oDXWpqPtEjo49Dk07Sgy176iCU9zRQuhvZS5zexAekqKEpYjKGpqXUuxAKYelJi5ZaZaNZ8h0H_u_9bZouOBH9-Uy4i; expires=Sun, 24-Feb-2013 15:06:54 GMT; path=/; domain=.google.co.in; HttpOnly

P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."

Server: gws

X-XSS-Protection: 1; mode=block

X-Frame-Options: SAMEORIGIN

Transfer-Encoding: chunked

--- Reading from Stream and Writing to Stream ---
Output Continue

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/