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

后端 未结 11 1473
攒了一身酷
攒了一身酷 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 = "subdata2";
    
    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 response = multipart.finish();         
        for (String line : response) {
            System.out.println(line);
        }
    }
    

提交回复
热议问题