resttemplate post json
时间: 2023-03-20 22:07:06 浏览: 108
RestTemplate是Spring框架提供的一个HTTP客户端工具,可以用来发送HTTP请求。使用RestTemplate发送POST请求时,可以通过以下步骤发送JSON数据:
1. 创建一个HttpHeaders对象,设置Content-Type为application/json。
2. 创建一个HttpEntity对象,将要发送的JSON数据和HttpHeaders对象传入。
3. 调用RestTemplate的postForObject方法,传入请求URL、HttpEntity对象和返回类型。
示例代码如下:
```
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求体
JSONObject requestBody = new JSONObject();
requestBody.put("name", "张三");
requestBody.put("age", 20);
HttpEntity<String> entity = new HttpEntity<>(requestBody.toJSONString(), headers);
// 发送POST请求
String url = "http://localhost:8080/user";
User user = restTemplate.postForObject(url, entity, User.class);
```
以上代码将发送一个POST请求到http://localhost:8080/user,并将JSON数据{name:"张三",age:20}作为请求体发送。请求头中的Content-Type为application/json。请求成功后,将返回一个User对象。