我有一些代碼,向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切換到HttpComponents後出現'格式不正確的請求'錯誤
代碼示例如下:
公地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
),但它仍然無法正常工作。
感謝您的答覆!我剛剛嘗試過三種可用的模式,但仍然無法正常工作。 – 2014-12-04 09:17:28
發佈HC3和HC4會話的線路/上下文日誌。有關詳細信息,請參閱HttpClient日誌指南。 – oleg 2014-12-04 09:18:52
我在相應的代碼示例下面添加了日誌。 – 2014-12-05 08:35:40