mrcrag
mrcrag

Reputation: 352

How to send both JSON and an attached file using HttpUrlConnection

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.

Upvotes: 0

Views: 296

Answers (1)

mrcrag
mrcrag

Reputation: 352

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

Upvotes: 1

Related Questions