使用HttpClient POST提交带有上传的表单

u19*_*964 5 html java forms http-post apache-httpclient-4.x

我有一个看起来像这样的html表单:

<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>
Run Code Online (Sandbox Code Playgroud)

我想编写一个自动创建产品的Java模块.这是我已经拥有的:

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); 
Run Code Online (Sandbox Code Playgroud)

这很好用,它可以创建名为"Product1"的新产品.但我不知道如何处理上传部分.我希望看起来像这样:

data.add(new BasicNameValuePair("product[name]", "Product1"));
Run Code Online (Sandbox Code Playgroud)

但它不是"Product1"而是文件.我阅读了HttpClient的文档,据说只有字符串.

有谁知道如何处理上传部分?

Pus*_*jee 8

依赖关系:

<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>
Run Code Online (Sandbox Code Playgroud)

代码:[棘手的部分是使用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();
Run Code Online (Sandbox Code Playgroud)