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.
This recipe sets the request body of an HTTP POST directly by
passing a File
object to method.setRequestBody()
. In addition to
accepting a File
object, setRequestBody( )
can accept an InputStream
or a String
. Any time a request body is populated,
the Content-Length
header must be
set to reflect the size of the request body by calling method.setRequestContentLength( )
. The
previous recipe sent parameters in an HTTP POST request body by calling
setParameter( )
and addParameter()
, and the Content-Length
and Content-Type
headers are automatically
populated when the method is executed. In this example, the Content-Type
header is not sent with the
request as the content can be any arbitrary textual or binary
data.