以下是一种解决方法,您可以使用HttpEntity
对象将请求体传递给Spring Rest Template,而不是使用LinkedMultiValueMap
。
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestClient {
public static void main(String[] args) {
// 创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求体
String requestBody = "{\"name\":\"John\",\"age\":30}";
// 创建HttpEntity对象并设置请求头和请求体
HttpEntity requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
ResponseEntity response = restTemplate.exchange("http://example.com/api/endpoint", HttpMethod.POST, requestEntity, String.class);
// 处理响应
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
System.out.println("Response Body: " + responseBody);
} else {
System.out.println("Request failed with status code: " + response.getStatusCodeValue());
}
}
}
在上面的示例中,我们首先创建一个RestTemplate
对象,然后设置请求头为Content-Type: application/json
。然后,我们创建一个包含请求体和请求头的HttpEntity
对象。接下来,我们使用exchange
方法发送POST请求,并将HttpEntity
作为参数传递给它。最后,我们可以通过ResponseEntity
对象获取响应体并进行处理。