Http Post using Apache http client

In this article, let’s discuss about how to post data to any Http URL using Apache http client api.

HTTP protocol has two basic methods GET and POST.
• GET method is used to receive data from a Web server.
• POST method is used to send some data to the Web server.

Consider the following url,
http://localhost:8080/httppost/postDataReceiverServlet?userCount=10

When you navigate to the above url in the browser, it posts the data 'userCount=10' to the given web server/port.

For example, if we are using Java Servlets, then the url will be mapped to the corresponding httpservlet. In the HttpServlet, doPost method will be called and business logic will be executed for the given data. Consider a scenario where you want to do the above operations programmatically. This can be achieved using the Apache http client api.

Consider the following class
PostDataSender.java

package in.techdive.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;

public class PostDataSender
{

        public static void main(String[] args) throws Exception
        {
                PostDataSender ps = new PostDataSender();
                ps.postData();
        }

        public int postData() throws Exception
        {
                int returnCode = 0;
                try
                {
                        HttpClient client = new HttpClient();
                        client.getParams().setParameter("http.useragent", "Http Test Client");

                        // if the url to be accessed requires basic authentication, set the following parameters
                        client.getParams().setAuthenticationPreemptive(true);
                        client.getState().setCredentials(new AuthScope((String) "localhost", 8080, "realm"),
                        new UsernamePasswordCredentials("<userName>", "<passWord>"));
                        BufferedReader br = null;
                        String url = "http://localhost:8080/ExampleAjax/postDataReceiverServlet?userCount=10";
                        PostMethod method = new PostMethod(url);

                        try
                        {
                                returnCode = client.executeMethod(method);
                                System.out.println("HTTP Status Code is --" + returnCode + "\n");
                                if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED)
                                {
                                        System.err.println("The Post method is not implemented by this URI");

                                        // still consume the response body
                                        method.getResponseBodyAsString();
                                }
                                else
                                {
                                        System.out.println("in else part..");
                                        br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                                        String readLine;
                                        while (((readLine = br.readLine()) != null))
                                        {
                                                System.out.println(readLine);
                                        }
                                }
                        }
                        catch (Exception e)
                        {
                                System.err.println(e);
                        }
                        finally
                        {
                                method.releaseConnection();
                                if (br != null)
                                        try
                                        {
                                                br.close();
                                        }
                                        catch (Exception fe)
                                        {
                                        }
                        }
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                }
                return returnCode;
        }
}

The above code accesses the given url and posts the data 'userCount=10'. We have used the Post Method class to post the data to the url. Then based on the http response code we are printing the output.

We can test the above class using a simple Servlet as follows.

PostDataReceiverServlet.java

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostDataReceiverServlet extends HttpServlet
{
        public PostDataReceiverServlet()
        {
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
                super.doGet(req, resp);
        }

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
                System.out.println("Inside post method...");
                System.out.println("userCount -> " + req.getParameter("userCount"));
                PrintWriter out = resp.getWriter();
                out.println("userCount -> " + req.getParameter("userCount"));
                super.doPost(req, resp);
        }
}

Whenever the above url is accessed the doPost method in the Servlet needs to be called.

In this way, we can post data to a url using Apache http client api.

Technology: 

Search