【发布时间】:2016-05-22 06:49:29
【问题描述】:
我正在使用 Apache HttpComponents v4.3.6(maven httpclient 和 httpmime)。我需要将文件数据作为多部分上传。有效的 Fiddler 命令如下所示。
Fiddler 上的请求标头:
Content-Type: multipart/form-data; boundary=c2d7073062e24d86ad739647574e14b9
Accept: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0
Fiddler 上的请求正文:
--c2d7073062e24d86ad739647574e14b9
Content-Disposition: form-data; name="categoryFile"; filename="self-classification-categories.tsv"
585743 583099 Existing Catrali 4Category ch Description of 4 Existing Category false false false Some notes 4 relating to Existing Category
--c2d7073062e24d86ad739647574e14b9--
文件的实际内容在哪里:
585743 583099 Existing Catrali 4Category ch Description of 4 Existing Category false false false Some notes 4 relating to Existing Category
现在,我正在尝试使用 Apache Http 客户端实现这个发布请求(如上所述),但不知道如何实际执行。要将上述请求转换为Java(1.8),我尝试了:(边界值:c2d7073062e24d86ad739647574e14b9)
httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost( createPostURI( host, path ) );
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0");
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=c2d7073062e24d86ad739647574e14b9");
httpPost.setHeader("Accept", "application/json");
String fileContent = "--c2d7073062e24d86ad739647574e14b9\r\nContent-Disposition: form-data; name=\"categoryFile\"; filename=\"self-classification-categories.tsv\""+
"\r\n\r\n"+
"585743 583099 Existing Catrali 4Category ch Description of 4 Existing Category false false false Some notes 4 relating to Existing Category"
+"\r\n--c2d7073062e24d86ad739647574e14b9--";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setBoundary("c2d7073062e24d86ad739647574e14b9");
builder.addTextBody("body", fileContent,ContentType.MULTIPART_FORM_DATA);
HttpEntity entity = builder.build();
httpPost.setEntity( entity );
response = httpclient.execute( httpPost, new GenericResponseHandler() );
我确信我在 Java 中制作请求正文的方式是错误的。 因此,我看到 403 错误,这是一种误导,因为我正在调用的 REST api 会引发此错误当它没有看到预期的格式时。我将不胜感激。
提前致谢。
【问题讨论】:
-
403 在服务器拒绝访问时出现。你的代码对我来说看起来不错。您也可以尝试从文件中读取正文内容并使用它吗?
标签: java http post multipartform-data multipart