How to use Post Method using Apache HttpClient 4


[tweet-dzone]HttpClient is an apache java library that can be used to read pages over http. It can be used mainly for webpages and provide a well defined API that can handle Cookies, Sessions,... It offers support for both Get and Post methods, so it's very useful for writing http java clients that can login and perform different actions on webpages.

Starting with the version 4 the classes were drastically changed. Old tutorials don't works anymore and the class names and methods were changed to some degree which makes old code pretty useless if you want to switch to a version 4.

Here is a small snippet which shows how to invoke a webpage via post method and how to pass post parameters. In real scenarios post parameters can be used to pass login informations. The snippet uses the method to Convert Input Stream To String from the previous post:

package com.factorypattern.httpclient;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class PostRequestClient {

    public static void main(String[] args) throws Exception {
        // prepare post method
        HttpPost post = new HttpPost("");
        // add parameters to the post method
        List <NameValuePair> parameters = new ArrayList <NameValuePair>(); 
        parameters.add(new BasicNameValuePair("param1", "value1")); 
        parameters.add(new BasicNameValuePair("param2", "value2")); 
        UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
        // create the client and execute the post method
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(post);
        // retrieve the output and display it in console 

     * method to convert an InputStream to a string using the BufferedReader.readLine() method
     * this methods reads the InputStream line by line until the null line is encountered
     * it appends each line to a StringBuilder object for optimal performance 
     * @param is
     * @return
     * @throws IOException
    public static String convertInputStreamToString(InputStream inputStream) throws IOException 
        if (inputStream != null) 
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) 

            return stringBuilder.toString();
            return null;