使用 Spring 发送多部分请求,每个部分都有特定的 header

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

Postman request

如图所示,对于 springboot 应用程序中多部分请求的特定部分,我想将 content-type 作为 application/json 发送。

使用 MultipartBodyBuilder 构建您的请求。

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);