Apache HttpClient making multipart form post

Use MultipartEntityBuilder from the HttpMime library to perform the request you want.

In my project I do that this way:

HttpEntity entity = MultipartEntityBuilder
    .create()
    .addTextBody("number", "5555555555")
    .addTextBody("clip", "rickroll")
    .addBinaryBody("upload_file", new File(filePath), ContentType.APPLICATION_OCTET_STREAM, "filename")
    .addTextBody("tos", "agree")
    .build();

HttpPost httpPost = new HttpPost("http://some-web-site");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();

Hope this will help.

(Updated this post to use MultipartEntityBuilder instead of deprecated MultipartEntity, using @mtomy code as the example)

Leave a Comment