Search code examples
javamultipartform-dataapache-httpclient-4.x

Apache HttpClient making multipart form post


I'm pretty green to HttpClient and I'm finding the lack of (and or blatantly incorrect) documentation extremely frustrating. I'm trying to implement the following post (listed below) with Apache Http Client, but have no idea how to actually do it. I'm going to bury myself in documentation for the next week, but perhaps more experienced HttpClient coders could get me an answer sooner.

Post:

Content-Type: multipart/form-data; boundary=---------------------------1294919323195
Content-Length: 502
-----------------------------1294919323195
Content-Disposition: form-data; name="number"

5555555555
-----------------------------1294919323195
Content-Disposition: form-data; name="clip"

rickroll
-----------------------------1294919323195
Content-Disposition: form-data; name="upload_file"; filename=""
Content-Type: application/octet-stream


-----------------------------1294919323195
Content-Disposition: form-data; name="tos"

agree
-----------------------------1294919323195--

Solution

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