Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using Apache HttpPost

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?

like image 552
Leszek Malinowski Avatar asked Sep 18 '25 23:09

Leszek Malinowski


1 Answers

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());
}
like image 92
ok2c Avatar answered Sep 21 '25 13:09

ok2c