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

Spring Boot 2.7升级3.1时HttpClient迁移HttpClient5遇依赖问题

解决方案:HttpClient5中找不到Timeout类的问题

问题原因

org.apache.hc.core5.util.Timeout类并不属于httpclient5依赖本身,它是httpcore5库的一部分——httpclient5依赖httpcore5,但部分构建工具或Spring Boot的默认依赖传递规则可能没有自动引入它,导致类路径缺失。

解决步骤

方式1:使用Spring Boot官方HttpClient Starter(推荐)

Spring Boot 3.x提供了专门的starter来管理HttpClient5相关依赖,自动处理版本兼容和依赖传递:

Gradle Kotlin DSL 配置

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-httpclient")
}

Maven 配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-httpclient</artifactId>
</dependency>

引入这个starter后,无需手动添加httpclient5或httpcore5,Spring Boot会自动引入匹配版本的依赖包。

方式2:手动添加httpcore5依赖

如果不想用starter,需要在依赖中同时加入httpclient5和httpcore5,注意版本保持一致(比如都用5.2.1):

Gradle Kotlin DSL 配置

dependencies {
    implementation("org.apache.httpcomponents.client5:httpclient5:5.2.1")
    implementation("org.apache.httpcomponents.core5:httpcore5:5.2.1")
}

Maven 配置

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents.core5</groupId>
    <artifactId>httpcore5</artifactId>
    <version>5.2.1</version>
</dependency>

验证修正后的代码

依赖添加完成后,你的HttpClient5代码可以正常运行:

import org.apache.hc.client5.http.config.RequestConfig
import org.apache.hc.core5.util.Timeout

class Boot3 {
    fun springBoot3() {
        val requestConfig = RequestConfig.custom()
            .setResponseTimeout(Timeout.ofSeconds(1L))
            .setConnectionRequestTimeout(Timeout.ofSeconds(3L))
            .build()
    }
}

额外说明:原Spring Boot 2.x中的setSocketTimeout对应HttpClient5的setResponseTimeout,你的代码映射是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:14