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

SpringBoot 2.7.8升级至3.2.1后RestTemplate调用报错求助

SpringBoot 3.2.1升级后RestTemplate调用出现NoSuchMethodError的解决方法

问题场景

将SpringBoot版本从2.7.8升级至3.2.1后,已更新Maven依赖为org.apache.httpcomponents.client5:httpclient5:5.2.1,调用以下RestTemplate方法时抛出错误:

public ResponseEntity<String> sendPostRequest(RestTemplate restTemplate, String url, Object requestBody, HttpHeaders headers) {
    HttpEntity<Object> request = new HttpEntity<>(requestBody, headers);
    return restTemplate.exchange(url, HttpMethod.POST, request, String.class);
}

错误日志:

[nio-8801-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/digital-provider] threw exception [Handler dispatch failed: java.lang.NoSuchMethodError: 'org.apache.hc.core5.http.ClassicHttpResponse org.apache.hc.client5.http.classic.HttpClient.executeOpen(org.apache.hc.core5.http.HttpHost, org.apache.hc.core5.http.ClassicHttpRequest, org.apache.hc.core5.http.protocol.HttpContext)'].

原因分析

该错误本质是类路径中存在版本不兼容的HttpComponents组件,具体是org.apache.hc.client5.http.classic.HttpClient的executeOpen方法签名不匹配,通常由以下情况导致:

  • 手动指定的httpclient5版本与SpringBoot 3.2.1内置依赖管理的版本冲突
  • 项目中残留了旧版HttpComponents依赖(比如httpclient 4.x系列)
  • httpclient5与对应的hc-core5版本不匹配

解决方案

1. 使用SpringBoot官方管理的HttpComponents版本

SpringBoot 3.2.1的依赖管理(BOM)中已经指定了兼容的httpclient5版本(5.2.3),无需手动指定版本,修改Maven依赖:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>

2. 排查并清理依赖冲突

执行Maven命令查看完整依赖树,定位冲突依赖:

mvn dependency:tree -Dverbose -Dincludes=org.apache.httpcomponents,org.apache.httpcomponents.client5

若发现旧版org.apache.httpcomponents:httpclient(4.x)或版本不一致的org.apache.hc.core5:hc-core5,在引入该依赖的模块中添加排除规则,示例:

<dependency>
    <groupId>第三方依赖groupId</groupId>
    <artifactId>第三方依赖artifactId</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </exclusion>
    </exclusions>
</dependency>

3. 确认RestTemplate的客户端工厂配置

如果自定义了RestTemplate实例,确保使用适配httpclient5的HttpComponentsClientHttpRequestFactory,示例配置:

@Bean
public RestTemplate restTemplate() {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    // 可根据需求添加超时等配置
    requestFactory.setConnectTimeout(Duration.ofSeconds(10));
    requestFactory.setConnectionRequestTimeout(Duration.ofSeconds(5));
    return new RestTemplate(requestFactory);
}

注:SpringBoot 3.x版本的HttpComponentsClientHttpRequestFactory已默认适配httpclient5,无需额外引入兼容包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:05:04