0

I need to send both JSON and a CSV file in a POST to a third party 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'

I would prefer to use HTTPUrlConnection but my understanding is that I can only send one type of data at a time. Maybe I could call Curl using ProcessBuilder but would like to find a native java solution.

4
  • How does the API expect the content? First the JSON and the CSV afterwards?
    – dan1st
    Commented Feb 8, 2021 at 21:12
  • Yes, based on their curl example (though I don't know if that translates to httpurlconnection).
    – mrcrag
    Commented Feb 9, 2021 at 13:27
  • Maybe gist.github.com/mcxiaoke/8929954 would help.
    – dan1st
    Commented Feb 9, 2021 at 14:04
  • Thanks dan1st. That might work but I'm going to go with the well supported Apache library (below).
    – mrcrag
    Commented Feb 9, 2021 at 18:50

1 Answer 1

1

After researching this, Apache's HTTPClient seems like the best solution: https://hc.apache.org/httpcomponents-client-5.0.x/index.html

After adding these dependencies:

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

I adapted this solution: 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();
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.