使用 Apache Http 4.5 MultipartEntityBuilder,似乎无法弄清楚为什么 StringBody(String,ContentType)构造函数实际上未在请求表单主体中输出 Content-Type。
public HttpRequestBase build() throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost("https://{server}/restapi/{apiVersion}/accounts/{accountId}/envelopes");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setBoundary("AAA");
//add form body
builder.addPart(generateJsonFormBodyPart());
//add file body
builder.addPart(generateFileFormBodyPart()); //<--intentionally omitted
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
return httpPost;
}
private FormBodyPart generateJsonFormBodyPart() throws UnsupportedEncodingException{
StringBody json = new StringBody(packageJson(), ContentType.APPLICATION_JSON); //<--THIS DOESN'T SEEM TO WORK
StringBuilder buffer = new StringBuilder();
buffer.append("form-data");
String contentDisposition = buffer.toString();
FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("application/json", json);
partBuilder.setField(MIME.CONTENT_DISPOSITION, contentDisposition);
FormBodyPart fbp = partBuilder.build();
return fbp;
}
文件部分输出正常,但我从对等端收到“错误请求”返回,我认为这是因为它具有非常特定的请求参数。
必填请求输出
接受:application/json Content-Type:multipart/form-data; boundary=AAA
--AAA Content-Type:application/json Content-Disposition:form-data
json 已删除
--AAA Content-Type:application/pdf Content-Disposition:文件; filename =“ test1.pdf”; documentid=1
文件已删除
实际的 Apache Http 4.5 输出
X-Docusign-Act-As-User:xyz@company.com Accept-Encoding:gzip,压缩 User-Agent:Apache-HttpClient/4.5(Java/1.8.0_65)Connect-Time:0 主机:requestb.in 连接:关闭 Content-Length:3178 授权:bearer xxxxrandomoauthtokenxxxxx Content-Type:multipart/form-data; boundary=AAA; charset=ISO-8859-1 通过:1.1 蔬菜 X-Request-Id:89cd1cf5-3615-41e8-84ba-cd076a03af67 Total-Route-Time:0
--AAA Content-Disposition:form-data // <--the 问题。应该是 application/json 不?
{“状态”:“创建”,“ emailBlurb”:“欢迎使用汇合”,“ emailSubject”:“欢迎使用汇合”,“文档”:{“名称”:“欢迎使用 Confluence.html”,“ documentId”:“ 1 “,” order“:” 1“},”收件人“:{}}
--AAA Content-Disposition:文件; filename =“ Welcome.html”; documentid=1 Content-Type:text/html; charset=ISO-8859-1
移除了 t m l 字符串
问:那么为什么 StringBody 构造函数中的 ContentType 被忽略?是否有解决方法,或者我做错了吗?
1 回答
我确信这是处理 StringBody 时 FormBodyPart.build()的 Apache Http Mime 中的错误。 4.5.2 发行说明中的证据表明,针对其他未输出“ Content-Type”的“ body”类型的错误修复程序支持此操作。我将记录一个缺陷。
解决方法:
奇迹般有效。