Use HttpClient POST to submit form with upload

廉价感情. 提交于 2019-12-01 17:52:35

问题


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 ?


回答1:


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();



回答2:


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



来源:https://stackoverflow.com/questions/11546609/use-httpclient-post-to-submit-form-with-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!