简体   繁体   English

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

[英]how do i create and post a multipart/mixed http request using Apache HttpComponentst?

I am using Apache HttpComponents v4.3.3 (maven httpclient and httpmime). 我正在使用Apache HttpComponents v4.3.3(maven httpclient和httpmime)。 I need to upload a file with some metadata. 我需要上传一个包含一些元数据的文件。 The curl command, which works, looks like the following. curl命令可以工作,如下所示。

curl -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=@somefile.zip;type=application/zip' https://www.some.domain/ curl -k -i -H“Content-Type:multipart / mixed”-X POST --form'field1 = val1'-form'field2 = val2'-form'file =@somefile.zip; type = application / zip'https://www.some.domain/

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");

However, after I use HttpClient to execute the HttpPost, I get the following exception (server code is also Java running on Jetty). 但是,在我使用HttpClient执行HttpPost之后,我得到以下异常(服务器代码也是在Jetty上运行的Java)。

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found org.apache.commons.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界

When I add a trace to curl 当我添加一个曲线卷曲

curl --trace - -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=@somefile.zip;type=application/zip' https://www.some.domain/ curl --trace - -k -i -H“Content-Type:multipart / mixed”-X POST --form'field1 = val1'-form'field2 = val2'-form'file =@somefile.zip; type = application / zip'https://www.some.domain/

I see that the form field/value pairs are set as HTTP headers. 我看到表单字段/值对被设置为HTTP标头。

Content-Disposition: form-data; 内容处理:表格数据; name=field1...value1 名称=字段1 ...值1

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. 我修改了一下并做了两件事让代码工作。

  • no longer use addPart(...) 不再使用addPart(...)
  • no longer set Content-Type header 不再设置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);

I also set HttpComponents to debug mode. 我还将HttpComponents设置为调试模式。

-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

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; 内容类型:multipart / form-data; boundary=5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc 边界= 5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc

Here my full code based in last response, but is slightly different, i had the same error but now works (thanks Jane!): 这里我的完整代码基于最后的响应,但略有不同,我有相同的错误,但现在工作(感谢简!):

public String sendMyFile(String p_file, String p_dni, String p_born_date) throws Exception {

    HttpClient httpclient = HttpClientBuilder.create().build();

    HttpPost    httppost = new HttpPost("http://localhost:2389/TESTME_WITH_NETCAT");

    /* Campos del formulario del POST que queremos hacer */
    File        fileIN  = new File(p_file);

    /* Construimos la llamada */
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();

    reqEntity
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody  ("p_file"               , fileIN)
            .addTextBody    ("p_dni"                , p_dni)
            .addTextBody    ("p_born_date"  , p_born_date);

    httppost.setEntity(reqEntity.build());

    System.out.println("executing request " + httppost.getRequestLine());

    HttpResponse response = httpclient.execute(httppost);

    System.out.println("1 ----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("2 ----------------------------------------");
    System.out.println(EntityUtils.toString(response.getEntity()));
    System.out.println("3 ----------------------------------------");

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        System.out.println("Response content length: " + resEntity.getContentLength());
    }

    return "OK";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 java 创建多部分/混合请求 - how to create multipart/mixed request using java 如何使用multipart将REQUEST值添加到HTTP POST方法,以将文件上传到Android中的PHP服务器? - How do I add REQUEST values to an HTTP POST method using multipart to upload a file to a PHP server in Android? 使用Apache Http Async Client上传包含分段POST请求的文件 - Upload file with multipart POST request using Apache Http Async Client Jboss RestEasy-如何使用multipart / mixed从multipart mime MultipartInput提取二进制数据 - Jboss RestEasy - How do i extract binary data from a multipart mime MultipartInput using multipart/mixed 在Java中生成混合/多部分HTTP请求 - Generate mixed/multipart HTTP request in Java 如何修复请求不包含multipart / form-data或multipart / mixed stream apache错误 - how to fix the request doesn't contain a multipart/form-data or multipart/mixed stream apache error 如何使用 Apache Http 组件中继来自 servlet 的 POST 请求? - How do I use Apache Http Components to relay a POST request from a servlet? 如何使用jax -rs创建POST请求 - How do i create a POST request using jax -rs 如何使用http客户端处理多部分请求 - how to handle multipart request using http client 如何使用 Apache HTTP 客户端将复杂参数传递给 POST 请求? - How to pass complex parameter to POST request using Apache HTTP client?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM