11.7. Making an HTTP POST Request

Problem

You need to supply parameters to a script or servlet using HTTP POST.

Discussion

Create a PostMethod and call setParameter( ) or addParameter() before you execute the method. The PostMethod will send a request with a Content-Type header of application/x-www-form-urlencoded, and the parameters will be sent in the request body. The following example demonstrates the use of PostMethod to send parameters:

               import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

HttpClient client = new HttpClient( );
        
// Create POST method
String url = "http://www.discursive.com/cgi-bin/jccook/param_list.cgi";
PostMethod method = new PostMethod( url );

// Set parameters on POST    
               method.setParameter( "test1", "Hello World" );
               method.addParameter( "test2", "This is a Form Submission" );
               method.addParameter( "Blah", "Whoop" );
               method.addParameter( new NameValuePair( "Blah", "Whoop2" ) );

// Execute and print response
client.executeMethod( method );
String response = method.getResponseBodyAsString( );
System.out.println( response );

method.releaseConnection( );

The param_list.cgi CGI script echoes all parameters received, and from the following output, you can see that three parameters were supplied to this script:

These are the parameters I received: test1: Hello World test2: This is a Form Submission Blah: Whoop ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.