本文介绍了如何使用Apache HttpComponentst创建和发布多部分/混合http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Apache HttpComponents v4.3.3(maven httpclient和httpmime)。我需要上传一个包含一些元数据的文件。 curl命令的工作原理如下:

I am using Apache HttpComponents v4.3.3 (maven httpclient and httpmime). I need to upload a file with some metadata. The curl command, which works, looks like the following.

curl post如下。

I have tried mimicking this curl post as the following.

HttpEntity entity = MultiPartEntityBuilder
 .create()
 .addPart("field1",new StringBody("val1",ContentType.TEXT_PLAIN))
 .addPart("field2",new StringBody("val2",ContentType.TEXT_PLAIN))
 .addPart("file", new FileBody(new File("somefile.zip"), ContentType.create("application/zip"))
 .build();
HttpPost post = new HttpPost("https://www.some.domain");
post.addHeader("Content-Type", "multipart/mixed");

但是,在我使用HttpClient执行HttpPost之后,我得到以下异常(服务器代码也是在Jetty上运行的Java)。

However, after I use HttpClient to execute the HttpPost, I get the following exception (server code is also Java running on Jetty).

一个跟踪到卷曲


我看到表单字段/值对被设置为HTTP头。

I see that the form field/value pairs are set as HTTP headers.

关于我在这里做错了什么想法?任何帮助是赞赏。

Any idea on what I'm doing wrong here? Any help is appreciated.

推荐答案

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

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.

这篇关于如何使用Apache HttpComponentst创建和发布多部分/混合http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:32