两个@RequestPart HttpUtils.postRequest怎么传
时间: 2024-01-04 12:19:34 浏览: 102
两个@RequestPart可以通过创建一个`MultiValueMap`对象来传递。`MultiValueMap`是Spring框架中的一个接口,它可以存储多个键值对,并且每个键可以对应多个值。你可以使用`org.springframework.util.LinkedMultiValueMap`类来实现`MultiValueMap`接口。
以下是一个示例代码,演示了如何使用`MultiValueMap`来传递两个@RequestPart参数:
```java
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
public class Example {
public static void main(String[] args) {
// 创建一个MultiValueMap对象
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
// 添加第一个@RequestPart参数
map.add("file1", new FileSystemResource("path/to/file1"));
// 添加第二个@RequestPart参数
map.add("file2", new FileSystemResource("path/to/file2"));
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 发送POST请求
String url = "http://example.com/upload";
restTemplate.postForObject(url, map, String.class);
}
}
```
请注意,上述示例中的`path/to/file1`和`path/to/file2`应替换为实际的文件路径。
阅读全文