How can I make a multipart/form-data POST request using Java?

后端 未结 11 1795
攒了一身酷
攒了一身酷 2020-11-22 05:56

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possi

11条回答
  •  佛祖请我去吃肉
    2020-11-22 06:34

    We use HttpClient 4.x to make multipart file post.

    UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost("...");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
    
    // This attaches the file to the POST:
    File f = new File("[/path/to/upload]");
    builder.addBinaryBody(
        "file",
        new FileInputStream(f),
        ContentType.APPLICATION_OCTET_STREAM,
        f.getName()
    );
    
    HttpEntity multipart = builder.build();
    uploadFile.setEntity(multipart);
    CloseableHttpResponse response = httpClient.execute(uploadFile);
    HttpEntity responseEntity = response.getEntity();
    

    Below is the original snippet of code with deprecated HttpClient 4.0 API:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    
    FileBody bin = new FileBody(new File(fileName));
    StringBody comment = new StringBody("Filename: " + fileName);
    
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("bin", bin);
    reqEntity.addPart("comment", comment);
    httppost.setEntity(reqEntity);
    
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    

提交回复
热议问题