用spring发送http请求
在Spring中,你可以使用RestTemplate
或WebClient
来发送HTTP请求。下面分别给出使用这两个类的简单示例。
现在pom.xml中导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId><version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>
1. 使用 RestTemplate:
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;public class HttpRequestExample {public static void main(String[] args) {// 创建 RestTemplate 实例RestTemplate restTemplate = new RestTemplate();// 设置请求 URLString url = "https://api.example.com/data";// 发送 GET 请求,并获取响应ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);// 获取响应体String responseBody = responseEntity.getBody();// 处理响应System.out.println("Response: " + responseBody);}
}
2、使用 WebClient:
import org.springframework.web.reactive.function.client.WebClient;public class HttpRequestExample {public static void main(String[] args) {// 创建 WebClient 实例WebClient webClient = WebClient.create();// 设置请求 URLString url = "https://api.example.com/data";// 发送 GET 请求,并获取响应String responseBody = webClient.get().uri(url).retrieve().bodyToMono(String.class).block();// 处理响应System.out.println("Response: " + responseBody);}
}