Search code examples
spring-bootmultipartform-dataresttemplate

Sending multipart requests using Spring Boot with specific header for every part


Postman request

https://i.sstatic.net/ILbhN.png]

As mentioned in image I would like to send content-type as application/json for a particular part of a multipart request in springboot application.


Solution

  • use MultipartBodyBuilder to build your request.

    HttpHeaders headers = new HttpHeaders();
    
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    
    headers.add("add custome header", "header value");
    
    MultipartBodyBuilder builder = new MultipartBodyBuilder();
    
    builder.part("json_part", "").header("Content-Type", "application/json");
    
    MultiValueMap<String, HttpEntity<?>> body = builder.build();
    
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(body, 
    headers);
    
    RestTemplate restTemplate = new RestTemplateBuilder().build();
    
    ResponseEntity<String> postResponse = restTemplate
        .postForEntity("yoururl", requestEntity, String.class);