Thursday, September 11, 2008

Jakarta Commons HttpClient API Example

The Jakarta Commons HttpClient component provides API's for accessing HTTP Resources. We can download HttpClient from Apache and use it.
The general process for using HttpClient consists of a number of steps:
  1. Create an instance of HttpClient.
  2. Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  3. Tell HttpClient to execute the method.
  4. Read the response.
  5. Release the connection.
  6. Deal with the response.
The following example shows, how we can use HttpClient for Submiting a form data to a URL.

import java.util.MissingResourceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

public class FundaHttpClient {
 public static boolean httpPost(HttpServletRequest request) {
   //URL to which we will submit the form data
   String strURL="";

   //create a instance of PostMethod
   PostMethod post = new PostMethod(strURL);
       //we are adding two parameter bride first name, and bride last name
     catch(Exception e){
      //Log::"Probably all required fields are not filled"+e.toString();
     HttpClient httpclient = new HttpClient();
     // Execute request
     try {
          // check the http status code  returned
          //if it is not == 200, then something is wrong and we return a false status code.
          int result = httpclient.executeMethod(post);
          //Display status code
          //Log "Response status code:"+result;
          // Display response
          //Log post.getResponseBodyAsString()
        catch(IOException ie){
           //Log IO exception occured while posting:"+ie.toString();
        finally {
             // Release current connection to the connection pool once you are done
    return status;      

Here //Log represent the Log service used for logging. We can replace each //Log with System.out.println or may be a full grown log service provider like log4j. The strUrl, in this case is String strURL="", it should be replaced with the actual post URL.

No comments :

Post a Comment