我有一些代码,向API发送multipart/form-data
请求。使用Apache的commons-httpclient 3.1它可以工作,但是切换到httpclient 4.3.5,我遇到了API的问题。您可以在下面找到两个代码示例。由于它与Salesforce API有关,我还向SFSE发布了一个问题,因为我仍然不确定它是否是我或他们身边的问题。但是,我的问题是:我是否正确地将代码迁移到4.3.5?如果是,httpclient的行为是否与执行multipart/form-data
请求有关?
代码示例如下:
commons-httpclient 3.1
String json = "{ \"body\":{ \"messageSegments\":[ { \"type\":\"Text\", \"text\":\"Here is another receipt.\" } ] }, \"capabilities\":{ \"content\":{ \"title\":\"receipt2\"} } }";
PostMethod filePost = new PostMethod("https://eu3.salesforce.com/services/data/v32.0/chatter/feed-elements/<some_feed_element_id>/capabilities/comments/items");
filePost.addRequestHeader("Authorization", token());
StringPart jsonPart = new StringPart("json", json);
jsonPart.setContentType(ContentType.APPLICATION_JSON.getMimeType());
FilePart filePart = new FilePart("feedElementFileUpload", file);
filePart.setContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
Part[] parts = { jsonPart, filePart };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
int response = httpclient.executeMethod(filePost);
有线/上下文日志:http://pastebin.com/RCg20Ygn
httpclient 4.3.5
String json = "{ \"body\":{ \"messageSegments\":[ { \"type\":\"Text\", \"text\":\"Here is another receipt.\" } ] }, \"capabilities\":{ \"content\":{ \"title\":\"receipt2\"} } }";
String attachmentName = "package.xml";
CloseableHttpClient client = HttpClientBuilder
.create()
.setDefaultHeaders(Lists.newArrayList())
.build();
HttpPost post = new HttpPost(
"https://eu3.salesforce.com/services/data/v32.0/chatter/feed-elements/<feed_element_id>/capabilities/comments/items"
);
post.addHeader(HttpHeaders.AUTHORIZATION, token());
post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.MULTIPART_FORM_DATA.getMimeType());
post.setEntity(
MultipartEntityBuilder.create()
.setStrictMode()
.addPart(
"json",
new StringBody(
json,
ContentType.APPLICATION_JSON
)
)
.addPart(
"feedElementFileUpload",
new FileBody(
new File(attachmentName),
ContentType.APPLICATION_OCTET_STREAM,
attachmentName
)
)
.build()
);
CloseableHttpResponse response = client.execute(post);
有线/上下文日志:http://pastebin.com/EHXd1y50
更新1:
我已经为MultipartEntityBuilder
(STRICT
,BROWSER_COMPATIBLE
,RFC6532
)尝试了所有三种可用模式,但它仍然无效。< / p>
答案 0 :(得分:1)
在使用MultipartEntityBuilder构建请求实体时尝试使用'浏览器兼容'模式而不是'strict'
更新1:
"Content-Type: multipart/form-data[\r][\n]"
这显然是错误的(缺少边界属性),可能是请求被拒绝的原因。
请删除此行,然后重试
post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.MULTIPART_FORM_DATA.getMimeType());