Standalone JAVA Class using Apache HTTP Client
A standalone java Class which can connect with a web application and get response code and Response stream using Apache HTTP Client
Introduction : Sometime we work on some
middleware project and face the issue for testing that application because that
middleware application is used by some third party. And we have to wait that
third party till their application gets up and able to do end to end testing.
There are certain other ways to overcome this problem, like a web application
can be made, from where data can be post on middle ware URL using HTTP Post or
Get method. But here I come up with some simple solution from which a simple
standalone java class can be used to test your middle ware application using
http client provided by Apache.
Note : It can access those URL or application only for which your network
Tools required for environment set up :
- Eclipse IDE (Any version which you prefer, or you can use any other ide in which you are comfortable or you can do it in notepad also).
- Jdk 1.5.
- Following jars
Step to create your client :
- Create java project in eclipse.
- Add the below jars in class path
- Now you are ready to create your standalone java class.
- Create the object of org.apache.commons.httpclient.methods.PostMethod (GetMethod can also be used but it depends on your requirement). In the constructor of PostMethod you have to pass the URL of application to which you are going to request. Below is the code snippet.
PostMethod post = new PostMethod("URL");
- Create HTTP client (org.apache.commons.httpclient.HttpClient) object.
HttpClient httpclient = new HttpClient();
- Now it's time to set the data that you need to send the application and the responsibility will be taken care by PostMethod object. Below is the code snippet to set your request entity.
String s = "abcdefghijklmn";
post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(s.getBytes()), s.length()));
- Now it's high time for HttpClient to execute the request. Make connection with the application server and provide you response using PostMethod object.
int result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
- You might face certificate issue with some URLs while using this code. No need to worry, Following are the steps to overcome this problem.
- Download certificate from particular site.
- Put it into your jre's security folder
- Execute following command on your command prompt
-import -trustcacerts -file /path/to/ca/certificatefile -alias CA_ALIAS -keystore
Consolidated Code :
* Created on Aug 23, 2011
To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
To change the template for this generated type comment go to
String s =
StringBuilder sb =
PostMethod post =
HttpClient httpclient =
result = httpclient.executeMethod(post);
status code: "