resttemplate.exchange怎么用
时间: 2023-05-20 07:07:21 浏览: 166
RestTemplate.exchange 是 Spring 框架中用于发起 HTTP 请求的方法,可以用于 GET、POST、PUT、DELETE 等请求方式。它的参数包括请求 URL、请求方法、请求头、请求参数等。
以下是使用 RestTemplate.exchange 方法的示例代码:
```java
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.example.com/user/{userId}/info";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("userId", "123");
HttpEntity<String> request = new HttpEntity<>("hello", headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class, uriVariables);
String responseBody = response.getBody();
```
其中,url 中可以使用占位符 {userId} 代表请求参数,uriVariables 可以存放占位符与对应值的映射关系,可以替换 url 中的参数。request 可以配置请求头与请求体,例如在示例中设置了一个名为 headers 的请求头。最后,RestTemplate.exchange 方法会返回一个 ResponseEntity 对象,其中包含了响应状态码、响应头、响应体等信息。在示例中,我们通过 response.getBody() 方法获取了响应体的内容。
希望这个回答能够帮助到你!