Use HttpClient POST to submit form with upload

apache-httpclient-4.x, forms, html, http-post, java

Solution

Dependencies:

<dependency>
 <groupid>org.apache.httpcomponents</groupid>
 <artifactid>httpclient</artifactid>
 <version>4.0.1</version>
</dependency>

<dependency>
 <groupid>org.apache.httpcomponents</groupid>
 <artifactid>httpmime</artifactid>
 <version>4.0.1</version>
</dependency>

Code:[Tricky part is use of MultipartEntity ]

HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost( url );
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
entity.addPart( paramName, new FileBody((( File ) paramValue ), "application/zip" ));
// For usual String parameters
entity.addPart( paramName, new StringBody( paramValue.toString(), "text/plain", Charset.forName( "UTF-8" )));
post.setEntity( entity );
// Here we go!
String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();

Problem

I have an html form that looks something like this: ``` <div class="field> <input id="product_name" name="product[name]" size="30" type="text"/> </div> <div class="field> <input id="product_picture" name="product[picture]" size="30" type="file"/> </div> ``` I want to write a Java module that automates the creation of product. Here is what I already have: ``` HttpHost host = new HttpHost("localhost", 3000, "http"); HttpPost httpPost = new HttpPost("/products"); List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>(); data.add(new BasicNameValuePair("product[name]", "Product1")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8"); httpPost.setEntity(entity); HttpResponse postResponse = httpClient.execute(host, httpPost); ``` This works fine, it is able to create new product with name "Product1". But I don't know how to handle the upload part. I would like something looks like this: ``` data.add(new BasicNameValuePair("product[name]", "Product1")); ``` but instead of "Product1" it is a File. I read the documentation of HttpClient it's said that there's only string. Does anyone know how to handle the uploading part ?

Original source

Related problems