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:
importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.HttpException;importorg.apache.commons.httpclient.methods.PostMethod; HttpClient client =newHttpClient( ); // Create POST method String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi"; PostMethod method =newPostMethod( weblintURL ); File file =newFile( "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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access