resttemplate x-www-form-urlencoded body 数组
时间: 2023-11-08 18:59:11 浏览: 122
浅析application/x-www-form-urlencoded和multipart/form-data的区别
在使用RestTemplate发送x-www-form-urlencoded格式的POST请求时,可以使用MultiValueMap来构建请求体,支持传递数组参数。以下是示例代码:
```java
// 导入所需的依赖
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 设置请求头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 构建请求体参数
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("param1", "value1");
body.add("param2", "value2");
body.add("param3", new String[]{"value3", "value4"}); // 数组参数
// 设置请求回调
RequestCallback requestCallback = restTemplate.httpEntityCallback(body, headers, HttpMethod.POST);
// 发送POST请求
ResponseEntity<String> response = restTemplate.execute("http://example.com/api", HttpMethod.POST, requestCallback, null);
// 获取响应结果
String responseBody = response.getBody();
```
阅读全文