You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebClient切换为HttpComponents后出现空响应,求正确配置方案

WebClient集成HttpComponents5异步客户端问题排查与修复

默认WebClient配置可正常运行:

WebClient webClient = WebClient.create(url);
Mono<String> mono = webClient.get().exchangeToMono(clientResponse -> {
    Mono<String> monos = clientResponse.bodyToMono(String.class);
    return monos;
});
Mono<ServerResponse> response = ServerResponse.ok().body(mono, String.class);

但替换为自定义HttpComponents异步客户端配置后,出现ERR_EMPTY_RESPONSE错误且请求未发送:

HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();
CloseableHttpAsyncClient closeableHttpAsyncClient = httpAsyncClientBuilder.build();
ClientHttpConnector clientHttpConnector = new HttpComponentsClientHttpConnector(closeableHttpAsyncClient);
WebClient webClient = WebClient.builder().baseUrl(url).clientConnector(clientHttpConnector).build();

问题根源

缺失客户端启动步骤:CloseableHttpAsyncClient实例创建后,必须调用start()方法完成初始化,否则客户端处于未就绪状态,无法执行网络请求。

修正后的完整配置

// 构建异步HttpClient并启动
HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();
CloseableHttpAsyncClient closeableHttpAsyncClient = httpAsyncClientBuilder.build();
closeableHttpAsyncClient.start(); // 关键:启动客户端

// 绑定到WebClient
ClientHttpConnector clientHttpConnector = new HttpComponentsClientHttpConnector(closeableHttpAsyncClient);
WebClient webClient = WebClient.builder()
        .baseUrl(url)
        .clientConnector(clientHttpConnector)
        .build();

// 后续请求逻辑与原代码一致
Mono<String> mono = webClient.get().exchangeToMono(clientResponse -> {
    return clientResponse.bodyToMono(String.class);
});
Mono<ServerResponse> response = ServerResponse.ok().body(mono, String.class);

额外注意事项

  • 确保依赖版本匹配:Spring Boot 3.0.1适配HttpClient5 5.2版本,无需额外调整版本号(spring-boot-starter-parent已做版本管理)。
  • 若使用Spring容器管理,建议将CloseableHttpAsyncClient声明为Bean,同时处理启动与关闭的生命周期:
@Bean
public CloseableHttpAsyncClient closeableHttpAsyncClient() {
    CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    return client;
}

@Bean
public WebClient webClient(CloseableHttpAsyncClient httpClient) {
    ClientHttpConnector connector = new HttpComponentsClientHttpConnector(httpClient);
    return WebClient.builder()
            .baseUrl(url)
            .clientConnector(connector)
            .build();
}

@PreDestroy
public void shutdownHttpClient(CloseableHttpAsyncClient httpClient) throws IOException {
    httpClient.close();
}

内容的提问来源于stack exchange,提问作者patsw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:10:42