Apache HttpClient making multipart form post

后端 未结 3 866
暖寄归人
暖寄归人 2020-11-27 11:39

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 (

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 12:18

    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.create("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)

提交回复
热议问题