RestTemplate发送multipart/form-data请求,文件类型为MultipartFile

 

 

private ResponseEntity<String> uploadFileToRemote(File file) throws IOException {
    String url = "http://example.com/upload";
    RestTemplate restTemplate = new RestTemplate();

    // Set the headers for the request
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    // Create the parameters and add the file
    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
    parameters.add("file", new FileSystemResource(file));

    // Add the additional parameter
    parameters.add("info", "123");

    // Create the request entity using the parameters and headers
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(parameters, headers);

    // Send the request
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

    return response;
}


在这个示例中,我们首先创建了一个RestTemplate实例,并将Content-Type请求头设置为multipart/form-data类型。

接着,我们创建了一个MultiValueMap参数,并将新文件添加到参数中。我们还添加了一个名为"info"的参数,值为"123"。

然后,我们使用请求头和参数创建一个HttpEntity,并将其作为参数传递给exchange()方法。

最后,我们返回响应。
 
posted @ 2023-03-07 11:11  非帆丶  阅读(2045)  评论(0编辑  收藏  举报