Simple HTTP POST Request
Commons Http Client is a HTTP agent implementation in java supporting
client-side authentication, HTTP state management and HTTP connection management.
This requires the libraries httpclient-4.1.2.jar, httpcore-4.1.2.jar,
httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and
commons-logging-1.1.1.jar to be in classpath.
The following example shows how to make Http Post request through Http Client.
package com.bethecoder.tutorials.commons_httpclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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;
import org.apache.http.util.EntityUtils;
public class SimplePostRequestTest {
/**
* @param args
*/
public static void main ( String [] args ) {
HttpClient httpclient = new DefaultHttpClient () ;
HttpPost httppost = new HttpPost ( "http://localhost:8080/HTTP_TEST_APP/postreq.jsp" ) ;
System.out.println ( "Requesting : " + httppost.getURI ()) ;
try {
List <NameValuePair> nvps = new ArrayList <NameValuePair> () ;
nvps.add ( new BasicNameValuePair ( "user" , "venakta sudhakar" )) ;
nvps.add ( new BasicNameValuePair ( "password" , "abcd1234" )) ;
httppost.setEntity ( new UrlEncodedFormEntity ( nvps, HTTP.UTF_8 )) ;
HttpResponse response = httpclient.execute ( httppost ) ;
System.out.println ( "\n\nResponse : " ) ;
if ( response.getEntity () != null ) {
System.out.println ( EntityUtils.toString ( response.getEntity ())) ;
}
} catch ( UnsupportedEncodingException e ) {
e.printStackTrace () ;
} catch ( ClientProtocolException e ) {
e.printStackTrace () ;
} catch ( IOException e ) {
e.printStackTrace () ;
} finally {
httpclient.getConnectionManager () .shutdown () ;
}
}
}
A simple Web Application which prints the request headers, parameters and body through JSP.
It gives the following output,