![](/img/trans.png)
[英]How to send POST request using HTTPURLConnection with JSON data
[英]How to send both JSON and an attached file using HttpUrlConnection
我需要在 POST 中將 JSON和CSV 文件發送給第三方 API:
curl -H "aToken:$TOKEN" --form-string 'json={"project": "1234", "template": "5678","data":[{"date": "2017-05-26","place": "my house"}, {"person":"alice"}]}' -F 'file=@path/to/file.csv' 'https://the.api.com/api/23/postData'
我更喜歡使用 HTTPUrlConnection 但我的理解是我一次只能發送一種類型的數據。 也許我可以使用 ProcessBuilder 調用 Curl 但想找到一個原生 java 解決方案。
經過研究,Apache的HTTPClient似乎是最好的解決方案: https://hc.apache.org/httpcomponents-client-5.0.x/index.ZFC35FDC70D5FC69D2369883A8EZ7
添加這些依賴項后:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
我調整了這個解決方案: Apache HttpClient making multipart form post
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("ID", "1234")
.addBinaryBody("CSVfile", new File("c:\\temp\\blah.csv"), ContentType.create("application/octet-stream"), "filename")
.build();
HttpPost httpPost = new HttpPost("http://www.apiTest.com/postFile");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.