且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Apache HttpComponentst创建和发布多部分/混合http请求?

更新时间:2022-05-05 06:37:12

我修改了一点,做了两件事情让代码工作。

I tinkered a bit and did two things to get the code working.


  • 不再使用addPart(...)

  • 不再设置Content-Type标题

以下是修改后的代码段,以便任何人感兴趣。

Here's the revised snippet that's working in case anyone is interested.

HttpEntity entity = MultipartEntityBuilder
 .create()
 .addTextBody("field1","val1")
 .addTextBody("field2","val2")
 .addBinaryBody("file", new File("somefile.zip"),ContentType.create("application/zip"),"somefile.zip")
 .build();
HttpPost post = new HttpPost("https://www.some.domain");
post.setEntity(entity);



我还将HttpComponents设置为调试模式。

I also set HttpComponents to debug mode.


-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG

事实证明,每个零件现在有边界。更好的是,Content-Type和边界是自动生成的。

It turns out that each part now has a boundary. Even better yet, the Content-Type and boundary are autogenerated.


Content-Type:multipart / form-data; boundary = 5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc

Content-Type: multipart/form-data; boundary=5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc