5

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 ?

u19964
  • 3,255
  • 4
  • 21
  • 28
  • 1
    Check out http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java – jfocht Jul 18 '12 at 17:13
  • So the solution is to use MultipartEntity instead of UrlEncodedFormEntity :-) – u19964 Jul 18 '12 at 19:14

2 Answers2

8

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();
Georgios Syngouroglou
  • 18,813
  • 9
  • 90
  • 92
Puspendu Banerjee
  • 2,631
  • 16
  • 19
0

Another faster way of playing around with HTTP request is to use curl.

u19964
  • 3,255
  • 4
  • 21
  • 28