如何使用 HttpUrlConnection 发送 JSON 和附件

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.html

添加这些依赖项后:

<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>

我采用了这个解决方案:

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();