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

Spring Boot 3.1.x迁移编译报错:无法访问HttpClient类

Spring Boot 3.1.x 适配 HttpClient 解决方案

1. 替换依赖

Spring Boot 3.x 已全面适配 Apache HttpClient 5.x,需将原 4.x 依赖替换为 HttpClient5:

原依赖:

implementation 'org.apache.httpcomponents:httpclient:4.5.14'

替换为(推荐使用 Spring Boot 依赖管理自动匹配兼容版本):

implementation 'org.apache.httpcomponents.client5:httpclient5'

若需指定版本,可使用适配 Spring Boot 3.1.x 的稳定版:

implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'

2. 修改导入包

HttpClient5 调整了包路径和类名,需替换原导入:

原导入:

import org.apache.http.impl.client.ClosableHttpClient;

替换为:

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

注意:类名拼写为 CloseableHttpClient(首字母 C 大写),包路径变更为 org.apache.hc.client5.http.impl.classic

3. 代码调整

修正 Bean 方法参数类型

原代码中方法参数类型与 Spring Boot 3.x 适配的 HttpComponentsClientHttpRequestFactory 所需类型不匹配,需同步修改参数类型:

修改后的完整代码:

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

@Configuration
public class A {

    // other code blocks

    @Bean
    @DependsOn({"httpclient"})
    public ClientHttpRequestFactory reqFactory(CloseableHttpClient httpClient){ 
        return new HttpComponentsClientHttpRequestFactory(httpClient);
    }
}

其他关联代码调整(若有)

如果项目中还有其他 HttpClient 4.x 相关代码,需同步替换为 HttpClient5 对应类:

  • 构建客户端的 HttpClients → org.apache.hc.client5.http.impl.classic.HttpClients
  • 请求配置类 RequestConfig → org.apache.hc.client5.http.config.RequestConfig

原因说明

Spring Boot 3.x 升级了底层依赖的 HttpClient 版本,从 4.x 切换至 5.x,两者的包结构、类名存在差异;同时 Spring 提供的 HttpComponentsClientHttpRequestFactory 已适配 HttpClient5 的 API,因此必须同步升级依赖并调整代码中的类引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:46:06