【问题标题】:How to send both JSON and an attached file using HttpUrlConnection如何使用 HttpUrlConnection 发送 JSON 和附件
【发布时间】:2021-05-12 11:59:22
【问题描述】:

我需要在 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 解决方案。

【问题讨论】:

  • API 如何期望内容?首先是 JSON,然后是 CSV?
  • 是的,基于他们的 curl 示例(虽然我不知道这是否会转化为 httpurlconnection)。
  • 也许gist.github.com/mcxiaoke/8929954 会有所帮助。
  • 感谢 dan1st。这可能可行,但我将使用支持良好的 Apache 库(如下)。

标签: java json api post attachment


【解决方案1】:

经过研究,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>

我调整了这个解决方案: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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2014-12-06
    • 2012-05-12
    相关资源
    最近更新 更多