如何使用Spring Boot发送一个包含查询参数fecpNo=CFA20240711001和tcpNo=TCP-123的HTTP GET请求?
时间: 2024-11-12 13:35:17 浏览: 43
在Spring Boot中,你可以使用`RestTemplate`或者`WebClient`来发送HTTP GET请求,包括查询参数。这里我们以`RestTemplate`为例进行说明:
```java
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
// 创建一个RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 定义请求的URL,注意这里的 "?" 表示开始添加查询参数
String url = "http://example.com/api?fecpNo=CFA20240711001&tcpNo=TCP-123";
// 如果有需要,可以设置自定义的HttpHeaders
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); // 设置请求体的媒体类型
// 发送GET请求
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, headers);
// 获取响应结果
String responseBody = response.getBody();
```
如果你想使用`WebClient`,则可以这样做:
```java
import org.springframework.web.reactive.function.client.WebClient;
// 创建一个WebClient实例
WebClient webClient = WebClient.create("http://example.com");
// 构造请求头和查询参数
Mono<String> result = webClient.get()
.uri(uriBuilder -> uriBuilder.path("/api")
.queryParam("fecpNo", "CFA20240711001")
.queryParam("tcpNo", "TCP-123")
.build())
.accept(MediaType.APPLICATION_JSON) // 设置接受的媒体类型
.retrieve()
.bodyToMono(String.class);
// 获取响应结果
String responseBody = result.block(); // 均匀阻塞获取结果
```
阅读全文