springboot3使用httpclient5
时间: 2025-02-07 21:37:58 浏览: 89
### 配置 Apache HttpClient 5 在 Spring Boot 3
为了在Spring Boot 3中使用HttpClient 5执行HTTP请求,首先需要确保项目包含了必要的依赖项。对于基于Maven的项目,在`pom.xml`文件中加入如下依赖:
```xml
<dependencies>
<!-- 使用父级springboot中的版本 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>${hutool.version}</version>
</dependency>
</dependencies>
```
上述配置引入了Apache HttpClient 5以及Hutool工具包,后者提供了额外的功能支持[^3]。
接着定义一个Bean来创建并配置`CloseableHttpAsyncClient`实例,这允许异步发送HTTP请求。下面是一个简单的例子展示如何实现这一点:
```java
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class HttpClientConfig {
@Bean(destroyMethod = "close")
public CloseableHttpAsyncClient httpClient() {
final var clientBuilder = HttpAsyncClients.custom();
// 可在此处设置代理、SSL上下文等
final var asyncClient = clientBuilder.build();
asyncClient.start();
return asyncClient;
}
}
```
有了这个客户端之后就可以编写服务类来进行实际的数据获取操作了。这里给出一段代码片段用来发起GET请求,并打印返回的结果:
```java
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncRequestService {
private static final Logger log = LoggerFactory.getLogger(AsyncRequestService.class);
private final CloseableHttpAsyncClient httpClient;
@Autowired
public AsyncRequestService(CloseableHttpAsyncClient httpClient) {
this.httpClient = httpClient;
}
@Async
public void fetchAndPrint(String url) throws Exception {
SimpleHttpRequest request = new SimpleHttpRequest("GET", url);
Future<SimpleHttpResponse> futureResponse = httpClient.execute(request, null);
try {
SimpleHttpResponse response = futureResponse.get(); // blocking call to get the result
int statusCode = response.getCode();
String responseBody = response.getBodyText();
log.info("Status code: {}", statusCode);
log.info("Response body: {}", responseBody);
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
```
这段代码展示了如何利用之前配置好的`httpClient`对象去发出异步请求,并通过日志记录器输出服务器响应的内容。注意这里的`@Async`注解意味着方法将在单独线程上运行;因此还需要适当配置@EnableAsync启用异步调用的支持[^1]。
阅读全文
相关推荐


















