Apache HttpClient 制作多部分表单帖子

我对HttpClient非常环保,我发现缺乏(和/或明显不正确)的文档非常令人沮丧。我正在尝试使用Apache Http Client实现以下帖子(下面列出),但不知道如何实际操作。下周我将把自己埋在文档中,但也许更有经验的HttpClient程序员可以更快地给我一个答案。

发布:

Content-Type: multipart/form-data; boundary=---------------------------1294919323195
Content-Length: 502
-----------------------------1294919323195
Content-Disposition: form-data; name="number"

5555555555
-----------------------------1294919323195
Content-Disposition: form-data; name="clip"

rickroll
-----------------------------1294919323195
Content-Disposition: form-data; name="upload_file"; filename=""
Content-Type: application/octet-stream


-----------------------------1294919323195
Content-Disposition: form-data; name="tos"

agree
-----------------------------1294919323195--

答案 1

使用 HttpMime 库中的 MultipartEntityBuilder 执行所需的请求。

在我的项目中,我是这样做的:

HttpEntity entity = MultipartEntityBuilder
    .create()
    .addTextBody("number", "5555555555")
    .addTextBody("clip", "rickroll")
    .addBinaryBody("upload_file", new File(filePath), ContentType.APPLICATION_OCTET_STREAM, "filename")
    .addTextBody("tos", "agree")
    .build();

HttpPost httpPost = new HttpPost("http://some-web-site");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();

希望这会有所帮助。

(使用@mtomy代码作为示例,更新了这篇文章以使用MultipartEntityBuilder而不是已弃用的MultipartEntity)


答案 2

多部分实体现在显示为已弃用。我正在使用apache httpclient 4.3.3 - 有谁知道我们应该使用什么?我发现谷歌搜索充满了多部分实体示例,我找不到任何东西。– vextorspace Mar 31 '14 at 20:36

下面是 HttpClient 4.3.x 中的示例代码

http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

import org.apache.http.entity.mime.MultipartEntityBuilder;

HttpPost httppost = new HttpPost("http://localhost:8080" +
        "/servlets-examples/servlet/RequestInfoExample");

FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

HttpEntity reqEntity = MultipartEntityBuilder.create()
        .addPart("bin", bin)
        .addPart("comment", comment)
        .build();


httppost.setEntity(reqEntity);

要使用类 MultipartEntityBuilder,您需要 httpmime,它是 HttpClient 的子项目

HttpClient 4.3.x:

http://hc.apache.org/httpcomponents-client-4.3.x/index.html

httpmime 4.3.x:

http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/dependency-info.html