Simulate A Post Request Using Java

Today, i’ll do a simple example on how to simulate a http post request using Apache Common Http Components. This is a usefull utility, because i use it heavily on many projects, specially to do a simple messaging between desktop clients and the server side. Very simple, very lightweight and also very reliable.

Okay, first i start with the server version of the application. I create a new WebProject on Netbeans, create a simple servlet and deploy it on tomcat. This is a very simple servlet to print on netbeans console and give response whether 0 if failed, or 1 if succeed.

package com.edw.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class LoginServlet extends HttpServlet {
    
    private Logger logger = Logger.getLogger(LoginServlet.class);
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            logger.debug("receiving post " + username + " and " + password);
            response.getWriter().write("1");
        } catch (Exception e) {
            logger.error(e,e);
            response.getWriter().write("0");
        }                
    }
}

As usual, i register my servlet on web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>com.edw.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

And now is my client’s side Java application.

package com.edw.postsimulator;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
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.util.EntityUtils;

public class PostSimulator {
    
    // this is your target url
    private static String url = "http://localhost:8084/WebTestPost/loginServlet";
    
    public static void main(String[] args) throws Exception  {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // set the parameters
        List <NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "edwin"));
        nvps.add(new BasicNameValuePair("password", "dodol"));

        // set the encoding
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        // send the http request and get the http response
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
		
        // read the server's response contents
        System.out.println(EntityUtils.toString(resEntity));
    }
}

These are what is written on my Netbean’s console,

And this is my Netbean’s project configurations

Hope it helped others, Cheers :-[

Google+

2 Comments

Agung Setiawan

about 4 years ago

thanks for the tutorial :D

Reply

edwin

about 4 years ago

sama-sama gan :D

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)