【发布时间】:2012-07-17 19:08:34
【问题描述】:
我有一个看起来像这样的 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 的文档,据说只有字符串。
有人知道如何处理上传部分吗?
【问题讨论】:
-
所以解决方案是使用 MultipartEntity 而不是 UrlEncodedFormEntity :-)
标签: java html http-post forms apache-httpclient-4.x