使用restTemplate用json的格式调用远程接口
时间: 2024-06-08 09:11:55 浏览: 11
可以使用以下代码示例使用 `RestTemplate` 调用远程接口并将返回结果解析为 JSON 格式:
```java
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String url = "http://example.com/api/data";
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
String jsonResult = response.getBody();
// 解析 JSON 格式的返回结果
ObjectMapper objectMapper = new ObjectMapper();
MyDataObject dataObject = objectMapper.readValue(jsonResult, MyDataObject.class);
```
其中,`MyDataObject` 是你自己定义的数据对象,用于存储返回结果中的数据。你需要使用 Jackson 库中的 `ObjectMapper` 对象将 JSON 格式的字符串解析为 Java 对象。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)