11.8. Sending POST Data from a File

Problem

You need to send the data from a file in an HTTP POST request.

Solution

Create a PostMethod, create a File object, and call setRequestBody( ) and setRequestContentLength() on the method before it is executed. The PostMethod will send a request with a Content-Length header, which reflects the size of the file sent in the request body. The following example demonstrates the use of PostMethod to send data from a file in a request body:

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

HttpClient client = new HttpClient( );
        
// Create POST method
String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi";
PostMethod method = new PostMethod( weblintURL );

File file = new File( "project.xml" );
method.setRequestBody( new FileInputStream( file ) );
               method.setRequestContentLength( (int)file.length( ) );

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

method.releaseConnection( );

The previous example hits a CGI script, which echoes the contents of the request body. When this example is executed, the response body is printed with the contents of the file that was uploaded in an HTTP POST request.

Discussion

This recipe sets the request body of an HTTP POST directly by passing a File object to method.setRequestBody(). In addition to accepting ...

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.