一尘不染

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

java

在Apache Commons HttpClient的3.x版本中,可以进行multipart / form-data POST请求(2004年的示例)。不幸的是,这在HttpClient的4.0版本中不再可能。

对于我们的核心活动“ HTTP”,多部分内容超出了范围。我们很乐意使用由其他项目维护的多部分代码,但我对此一无所知。几年前,我们曾尝试将多部分代码移至commons编解码器,但我没有离开那里。Oleg最近提到了另一个包含多部分解析代码的项目,并且可能对我们的多部分格式代码感兴趣。我不知道目前的状态。(http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)

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


阅读 567

收藏
2020-02-29

共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();
2020-02-29