resttemplate 传参json编码怎么设置
时间: 2023-07-28 22:10:08 浏览: 133
在使用 RestTemplate 传参时,可以通过设置 `HttpEntity` 的 `ContentType` 为 `MediaType.APPLICATION_JSON`,并将参数对象使用 JSON 序列化工具(如 Jackson)转换成字符串后作为 `HttpEntity` 的 body 来实现 JSON 编码。
示例代码:
```java
RestTemplate restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
// 将参数对象转换成 JSON 字符串
String requestBody = objectMapper.writeValueAsString(requestObject);
// 设置 HttpEntity 的 ContentType 为 MediaType.APPLICATION_JSON
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, headers);
// 发送 POST 请求
ResponseEntity<ResponseType> responseEntity = restTemplate.postForEntity(url, httpEntity, ResponseType.class);
ResponseType responseBody = responseEntity.getBody();
```
阅读全文
相关推荐

















