如何使用Java发出多部分/表单数据POST请求?

2022-08-31 09:24:11

在Apache Commons HttpClient的3.x版本的日子里,可以提出多部分/表单数据POST请求(2004年的一个例子)。不幸的是,这在HttpClient的4.0版本中不再可能。

对于我们的核心活动“HTTP”,多部分有点超出范围。我们很想使用由其他项目维护的多部分代码,但我不知道任何部分代码。几年前,我们试图将多部分代码移动到commons-codec,但我没有在那里起飞。Oleg最近提到了另一个具有多部分解析代码的项目,并且可能对我们的多部分格式化代码感兴趣。我不知道目前的状况。(http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)

有没有人知道任何Java库允许我编写一个可以发出多部分/表单数据POST请求的HTTP客户端?

背景:我想使用Zoho Writer的远程API


答案 1

我们使用 HttpClient 4.x 来制作多部分文件发布。

更新:从 HttpClient 4.3 开始,某些类已被弃用。以下是新 API 的代码:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
    "file",
    new FileInputStream(f),
    ContentType.APPLICATION_OCTET_STREAM,
    f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

以下是带有已弃用的 HttpClient 4.0 API 的原始代码片段:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

答案 2

这些是我拥有的 Maven 依赖项。

Java 代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httpPost);

pom.xml中的 Maven Dependencies:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>

推荐