简体   繁体   中英

POST request with Multipart File and parameters in Java

I have POST API endpoint in Java , which is like below which is to be called for storing student marksheet in the portal.

POST API endpoint

/**
@param name
        Name of student
@param class
        Class of student
@param section
        Section of student
@param rollno
        Roll Number of student
@param file
        Marksheet of student in .xlsx format
**/
@PostMapping(value="/storeMarksheet", produces = "application/json")
public String performTaskAndSendResponse(
    @RequestParam String name,
    @RequestParam String class,
    @RequestParam String section,
    @RequestParam String rollno,
    @RequestPart(name=file) @ApiParam(".xlsx file") MultipartFile file
){
    System.out.println("Inside store marksheet endpoint") // not getting printed
    // Store marksheet and return response accordingly
}

And have written a function like below to call it

POST API function call

public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
    Map<String, Object> student = new HashMap<String, Object>;
    student.put("name", name);
    student.put("class", class);
    student.put("section", section);
    student.put("rollno", rollno);
    student.put("file", marksheet);

    String dataAsString = student.toString();
    String API = "https://somedomain.com/example/storeMarksheet";
    StringBuilder resp = new StringBuilder();
    String lineResponse = null;

    try{
        URL url = new URL(API);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Using HttpURL connection
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(dataAsString.getBytes("utf-8"));
        
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        while((lineResponse = br.readLine()) != null) resp.append(lineResponse.trim());

        System.out.println(resp.toString());
        return resp;
    }catch(Exception e){
        return null;
    }

}

However seems like the call is not going at all. Using HttpURLConnection for making http calls.

NOTE

  1. First priority is sending via HttpURLConnection only, if impossible then open to other solutions
  2. The above POST API endpoint is working perfectly in swagger.

Tried to do via HttpURLConnection but nothing worked for me. Therefore posting answer using another process

public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
    String responseStr = null;
    try{
        HttpPost req = new HttpPost("https://somedomain.com/example/storeMarksheet");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("name",name);
        builder.addTextBody("class",class);
        builder.addTextBody("section",section);
        builder.addTextBody("rollno",rollno);
        builder.addbinaryBody("file", marksheet.getBytes(), ContentType.DEFAULT_BINARY, marksheet.getOriginalFilename() );
    
        HttpEntity entity = builder.build();
        req.setEntity(entity);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse res = client.execute(req);
        responseStr = EntityUtils.toString(res.getEnity().toString());
        System.out.println(responseStr); 
    }catch(Exception e){
        //do something.. have put common exception for now
        
    }finally{
        try{
            res.close();
            client.close();
        }catch(Exception e){
            //do something.. have put common exception for now
        }
        return responseStr;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM