java - 使用 HttpClient POST 提交表单并上传

标签 java html http-post forms 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>

我想编写一个 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); 

这工作正常,它能够创建名为“Product1”的新产品。但我不知道如何处理上传部分。我想要这样的东西:

data.add(new BasicNameValuePair("product[name]", "Product1"));

但不是“Product1”,而是一个文件。我阅读了 HttpClient 的文档,据说只有字符串。

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

最佳答案

依赖关系:

<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>

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

关于java - 使用 HttpClient POST 提交表单并上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11546609/

相关文章:

java - 无法从 servlet 返回 CSS html

REST帖子格式

ajax - ajax POST 上的 IE 10 HTTP 401 错误

java - 带有 "IPv4"的类的驼峰命名法

html - 如果缓存日期超过特定日期,则告诉浏览器更新缓存

javascript - JS : How to hide parent div with multiple nested divs, 基于子 div 的内容

rest - Backbone Send Post 数据编码为查询字符串

java - 设置 JAVA_HOME 的 Grunt 任务

Java Swing : Resize JMenuItem's icon, 是自动还是以编程方式?

java - 如何检查计数器是否越界