I've got a curl call like this:
curl -i -X POST -H "Content-Type: multipart/form-data" -F "file=@data_test/json_test.json" http://domain.com/api/upload_json/
All I need to do is a Java implementation for this call. I've already made this code, but the file, which appears to server, seems to be null.
public static void uploadJson(String url, File jsonFile) {
try {
HttpPost request = new HttpPost(url);
EntityBuilder builder = EntityBuilder
.create()
.setFile(jsonFile)
.setContentType(ContentType
.MULTIPART_FORM_DATA)
.chunked();
HttpEntity entity = builder.build();
request.setEntity(entity);
HttpResponse response = getHttpClient().execute(request);
logger.info("Response: {}", response.toString());
} catch (IOException e) {
logger.error(e.getMessage());
}
}
What is the proper way to build this request?
CloseableHttpClient httpClient = HttpClientBuilder.create()
.build();
HttpEntity requestEntity = MultipartEntityBuilder.create()
.addBinaryBody("file", new File("data_test/json_test.json"))
.build();
HttpPost post = new HttpPost("http://domain.com/api/upload_json/");
post.setEntity(requestEntity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.print(response.getStatusLine());
EntityUtils.consume(response.getEntity());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With