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:- Create an instance of
HttpClient
. - 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.
- Tell
HttpClient
to execute the method. - Read the response.
- Release the connection.
- Deal with the response.
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.
Comments
Post a Comment