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.io.IOException;
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="http://www.nefunda.com/codes/submit.php";

   //create a instance of PostMethod
   PostMethod post = new PostMethod(strURL);
    
   try{
       //we are adding two parameter bride first name, and bride last name
       post.addParameter("bride_fname",bride_fname);
       post.addParameter("bride_lname",bride_lname);
     }
     catch(Exception e){
      status=false;
      //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;
          if(result!=200)status=false;
              
          // Display response
          //Log post.getResponseBodyAsString()
        } 
        catch(IOException ie){
           status=false;
           //Log IO exception occured while posting:"+ie.toString();
        }
        finally {
             // Release current connection to the connection pool once you are done
             post.releaseConnection();
        }
    
    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="http://www.nefunda.com/codes/submit.php", it should be replaced with the actual post URL.

No comments :

Post a Comment