Making HTTP POST Client Application using Java

What is on our mind when we see this title?. On Internet technology, we found often an interaction between user and a website. One of this interaction such as when user asked to input data on a website for some matters. When that’s happen, we can understand on that web application there’s some data inputed on a website actually.

On web programming we knew few methods on posting process, the first is post methods. Post methods is a data post mechanism, that in it’s process the post parameters explicitly cannot be seen on browsers address bar, while get methods is a posting data mechanism that the posting parameters explicitly seen on browsers address bar.

Now we will try to make a java console application, which this application have an ability to post to an URL within HTTP POST method. For this project we will need a server element. This element is used to catch the post action that we will do using this project application. We will make this server element using PHP script, so the element is more simple and easier to make. Let’s take a look out this PHP script below, this script is made in order to catch all the thrown data post.

 <?php
//define all param
$name = $_POST["name"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$address = $_POST["address"];

//print our all posted param
echo "Name : ".$name."<br>";
echo "Phone : ".$phone."<br>";
echo "Email : ".$email."<br>";
echo "Address : ".$address."<br>";

//other method to go to next process goes here...!!!

?>

That script is very simple, first, declare all parameters that thrown to this file, and then print out all those passed parameters. If you wants any other process after catch all parameters process such as save data process to a database, please do so, the important things is 5 lines of the beginning of the script still exist. On that above script, we use $_POST to catch all passed parameters, because out later application will be using HTTP POST method, if we use HTTP GET method, so the we cannot use this lines we have to use $_GET to catch all the passed parameters.

We named this PHP script as test.php, and then we have to put this file on our apache htdocs folder, let’s put this file on <apache_folder>/htdocs/server_hit/ where apache_folder is your apache-php installation directory. Then we run down our apache server and test this file by opening a browser and type http://localhost/server_hit/test.php on a it’s address bar. If we see the browser just like this below image, so our server element for this project is done.

php_post

And now we will make a java console application, that this application will shoot that URL. Our application will include libraries from the apache.common.project collection which is common-httpclient library, please download this library here. This common-httpclient library had a dependency of other apache.common.project which is common-logging library, so please download this common-logging library here.

If we have provided all the libraries, let’s code. This link is a complete source file of this application. We will discuss this code. On the source file we could see there’s 3 methods which is:

  1. public static Hashtable defineParamToPost.

  2. public static sendUrlPost.

  3. public static void main.

Those three methods is a static methods, which the 3rd method is a main method of our application, while others methods in this application can be called directly on a main method without declaring our application as a new object, because those both methods is also static.

Now let’s discuss each method, take a look to first method as shown below:

....
....
public static Hashtable defineParamToPost(String sParamName,
                              String sParamPhone,
                              String sParamEmail,
                              String sParamAddress) {
       Hashtable hash = new Hashtable();
       hash.put("name", sParamName);
       hash.put("phone", sParamPhone);
       hash.put("email", sParamEmail);
       hash.put("address", sParamAddress);
   return hash;

}

.....
.....

This method have a return value as Hashtable object and this method have 4 string type parameters. This method is processing a conversion of 4 string type parameters into a hashtable object and then return the process as a hashtable obejct.

Now let’s discuss 2nd method, sendUrlPost method. Let’s take a look on a few beginning lines of this method below:

......
......
......
public static String sendUrlPost(String Url, Hashtable hash,
                          int connectionTimeout, int readTimeout) {

System.out.println("Url To Post: " + Url);
System.out.println("Timeout limit for Connection :" + connectionTimeout + " milisecond");
System.out.println("Timeout limit for Read Response :" + readTimeout + " milisecond ");
System.out.println("Params to be posted on Hashtable Object : " + hash);

String sResponse = "";

Enumeration paramList = hash.keys();
Vector requestParamKey = new Vector(1, 1);
Vector requestParamValue = new Vector(1, 1);

System.out.println("Converting Hashtable to Vector....");

while (paramList.hasMoreElements()) {
 String name = (String) paramList.nextElement();
 String value = (String) hash.get(name);
 requestParamKey.addElement(name);
 requestParamValue.addElement(value);
 if (!paramList.hasMoreElements()) {
     break;
 }
}
System.out.println("Convert Hashtable to Vector done...");
......
......
......
}

On those code above, we can see we print out all the passed parameters to this method, and then after we declare String sResponse, we initialized a few objects which is Enumeration object and Vector object. And then we do loop to map the hashtable onto each Vector object that we have initialized before which is requestParamKey and requestParamValue. And then for the next process let’s take a look on the below code:

public static String sendUrlPost(String Url, Hashtable hash,
                           int connectionTimeout, int readTimeout) {
......
......
......

//create new HttpClient Object
HttpClient client = new HttpClient();

//Set Timeout till connection established
client.setConnectionTimeout(connectionTimeout);

// Set Timeout waiting for data
client.setTimeout(readTimeout);

int responseCode = -1;

// Create a method instance.
PostMethod method = new PostMethod(Url);
method.setHttp11(false);

String req_name = null;
String req_value = null;
......
......
}

On the next lines we could see, few methods of this common-httpclient library is used here. First step we could see there’s a making proces of HttpClient object, and then some property if this object is set. Those properties are Connection Time Out and Timeout, that the timeout property is a maximal time needed to read the result of the connection.

And then new object was made here above is PostMethod object, for this object the property http11 is set to false, because we don’t use it to create http connection. And then there’s a declaration of two string, both string has a null given value as an initialization. And now let’s take a look of others next code:

public static String sendUrlPost(String Url, Hashtable hash,
                            int connectionTimeout, int readTimeout) {
......
......
......

try {
   //iterate Vector contains http_post params
   System.out.println("Iterating Vector to map to post params...");
   for (int i = 0; i < requestParamKey.size(); i++) {
       req_name = (String) requestParamKey.elementAt(i);
       req_value = (String) requestParamValue.elementAt(i);
       method.addParameter(req_name, req_value);
   }

   System.out.println("Iterating Vector Done...");

   //execute Post Method
   System.out.println("Executing Http Method...");
   responseCode = client.executeMethod(method);
} catch (MalformedURLException mue) {
   mue.printStackTrace();
} catch (IOException ioe) {
   ioe.printStackTrace();
} catch (Exception runex) {
   runex.printStackTrace();
}

//printout Server Status
System.out.println("HttpResponseCode : " + responseCode);

......
......
}

On those lines we could see the post method execution is invoke here, after we iterate Vector object and then put each element and it’s value onto HTTP POST method parameters. Those task should be proces on try-catch block to avoid unexpected error such as Malformed URL, or any other catch. When this method was executed, server will return the HTTP STATUS, we can catch this status and then print it out onto a console.

Now, let’s take a look the last lines of this methods:

public static String sendUrlPost(String Url, Hashtable hash,
                             int connectionTimeout, int readTimeout) {
......
......
......

if (responseCode != 200) {
    // Release the connection.
    method.releaseConnection();
    System.out.println("Invalid HttpResponse: " + responseCode);
    return sResponse;
}

// Read the response body.
System.out.println("Reading the Response Body...!!!");
byte[] responseBody = method.getResponseBody();

if (responseBody != null) {
    System.out.println("Converting Response Body from byte array to String...");
    sResponse = new String(responseBody);
    if (sResponse != null) {
        sResponse = sResponse.trim();
    }
}

// Release the connection.
System.out.println("Releasing Connection...");
method.releaseConnection();

return sResponse;
}

On these last lines of this method, we see that if there’s not HTTP response return as 200, that’s mean our posting process will not be successful, because on HTTP response code, a successful connection to a server will be marked by HTTP status code 200. And then next line on this method is statement to read the resonse body of the server. Response body is view of a web page when we request the page on a web site.

The reading of this response body that exist on this method is read process of bytes that appear from the web page. On this method, this bytes was hold on an array of byte variable. And then the next process are converting this array of byte into a string variable, this string is needed to give return value of this method. The last process of this method is releasing the http connection.

That’s it, the discussion of both essential methods on this source file, while the main method, I think it’s easier to understand, because the main method is only processing the calls of these both essential method.

If we have done for this project, now we can test this application, i’ve tested on my side using IntelliJidea and the screen shot is below, and it’s running well, how bout you…?

runninghttppostclient

For the next future development, we can use this application consept to create an application that suitable for posting data into a server. This application might be a scheduled post that might be need to run periodically. It can be used too post the data that might be taken from a database, so the post will loop as much as the row on the database. Rather then we do posting manually it will waste a time, we can use this application consept and impelement anything that might be suitable for our needs.

 

I hope this usefull.

Menteng, January 15th 2008

 

josescalia

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s