spring发送http请求的api
时间: 2023-11-14 21:06:43 浏览: 54
Spring提供了多种发送HTTP请求的API,其中最常用的是使用RestTemplate和WebClient。
1. RestTemplate:
RestTemplate是Spring提供的传统的同步的HTTP客户端,它提供了多种发送HTTP请求的方法,包括GET、POST、PUT、DELETE等。
使用RestTemplate发送GET请求的示例代码如下:
```java
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://example.com/api/resource", String.class);
```
使用RestTemplate发送POST请求的示例代码如下:
```java
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("key1", "value1");
requestBody.put("key2", "value2");
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://example.com/api/resource", requestEntity, String.class);
String response = responseEntity.getBody();
```
2. WebClient:
WebClient是Spring 5引入的非阻塞的异步HTTP客户端,它基于Reactor提供了更高效的性能和更好的响应式编程支持。
使用WebClient发送GET请求的示例代码如下:
```java
WebClient webClient = WebClient.create();
Mono<String> responseMono = webClient.get()
.uri("http://example.com/api/resource")
.retrieve()
.bodyToMono(String.class);
responseMono.subscribe(response -> {
// 处理响应结果
});
```
使用WebClient发送POST请求的示例代码如下:
```java
WebClient webClient = WebClient.create();
Mono<String> responseMono = webClient.post()
.uri("http://example.com/api/resource")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(requestBody)
.retrieve()
.bodyToMono(String.class);
responseMono.subscribe(response -> {
// 处理响应结果
});
```
以上是Spring发送HTTP请求的两种常用方式,你可以根据实际需求选择使用RestTemplate还是WebClient。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)