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

后端 未结 11 1469
攒了一身酷
攒了一身酷 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:30

    We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java

    private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
    private static String subdata1 = "@@ -2,3 +2,4 @@\r\n";
    private static String subdata2 = "<data>subdata2</data>";
    
    public static void main(String[] args) throws Exception{        
        String url = "https://" + ip + ":" + port + "/dataupload";
        String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());
    
        MultipartBuilder multipart = new MultipartBuilder(url,token);       
        multipart.addFormField("entity", "main", "application/json",body);
        multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
        multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);        
        List<String> response = multipart.finish();         
        for (String line : response) {
            System.out.println(line);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:32

    My code for sending files to server using post in multipart. Make use of multivalue map while making request for sending form data

      LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("FILE", new FileSystemResource(file));
            map.add("APPLICATION_ID", Number);
    
       httpService.post( map,headers);
    
    

    At receiver end use

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
        public ApiResponse AreaCsv(@RequestParam("FILE") MultipartFile file,@RequestHeader("clientId") ){
    //code
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-22 06:35

    If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.

    httpclient-4.2.4:      423KB
    httpmime-4.2.4:         26KB
    httpcore-4.2.4:        222KB
    commons-codec-1.6:     228KB
    commons-logging-1.1.1:  60KB
    Sum:                   959KB
    
    httpmime-4.2.4:         26KB
    httpcore-4.2.4:        222KB
    Sum:                   248KB
    

    Code:

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    
    FileBody fileBody = new FileBody(new File(fileName));
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);
    
    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    ...
    

    Dependency in pom.xml:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.2.4</version>
    </dependency>
    
    0 讨论(0)
  • 2020-11-22 06:36

    Use this code to upload images or any other files to the server using post in multipart.

    import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    public class SimplePostRequestTest {
    
        public static void main(String[] args) throws UnsupportedEncodingException, IOException {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");
    
            try {
                FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
                StringBody id = new StringBody("3");
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("upload_image", bin);
                reqEntity.addPart("id", id);
                reqEntity.addPart("image_title", new StringBody("CoolPic"));
    
                httppost.setEntity(reqEntity);
                System.out.println("Requesting : " + httppost.getRequestLine());
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httppost, responseHandler);
                System.out.println("responseBody : " + responseBody);
    
            } catch (ClientProtocolException e) {
    
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        }
    
    }
    

    it requires below files to upload.

    libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

    0 讨论(0)
提交回复
热议问题