Apache HttpPost 多个文件上传失败并出现服务器错误 - 缺少初始多部分边界

Apache HttpPost Multiple Files upload failes with server error - Missing initial multi part boundary

我尝试使用 Apache Http 库上传多个文件。

   compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.6'

这是我上传文件的方式。

String url = "url";
File f1 = new File("file1");
File f2 = new File("file2");
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "multipart/form-data");
request.addHeader("Authorization", "Basic abcd=");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody fileBody1 = new FileBody(f1, ContentType.DEFAULT_TEXT);
FileBody fileBody2 = new FileBody(f2, ContentType.DEFAULT_TEXT);

multipartEntityBuilder.addPart("file_1_param", fileBody1);
multipartEntityBuilder.addPart("file_2_param", fileBody2);
HttpEntity httpEntity = multipartEntityBuilder.build();
request.setEntity(httpEntity);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
if (entity == null) {
    return;
}

InputStream is = entity.getContent();
String textResponse = InputStreamUtils.readText(is);
System.out.println(textResponse);

打印。

<pre>    Server Error</pre></p><h3>Caused by:</h3><pre>java.lang.RuntimeException: javax.servlet.ServletException: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: Missing initial multi part boundary
at com.ca.devtest.acl.servlet.filters.RemoteAuthenticationFilter.doFilter(RemoteAuthenticationFilter.java:285)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)

如果我只上传一个文件就可以了!

请注意,这不是重复的。这些链接显示引用服务器端问题的帖子。这个问题出在客户端。

Jetty throws "Missing content for multipart request" on multipart form request

我找到了解决办法。我想与其他人分享,这样您就可以 1) 学习如何上传文件和 2) 关注 HTTP headers.

当我将 FileBody 附加到 MultipartEntityBuilder 时,它会自动设置边界。我只是从代码

中删除了这一行
 request.addHeader("Content-Type", "multipart/form-data"); //Remove it

Example of a POST request with one or more files attached

The Multipart Content-Type

从 headers 中完全删除 content-type 选项以使其正常工作。

例子

headers = {
  'cache-control': 'no-cache',
  'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
  'postman-token': '26ef68f6-e579-a029-aec2-09b291678b4d',
  'storeid': '4223556'
}