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

RestAssured替换CoreConnectionPNames后出现Groovy类型转换异常如何解决

问题根因

你遇到的类型转换报错是RestAssured版本与Apache HttpClient 4的子版本不兼容导致的:

  • 你使用的RestAssured版本中,httpClientFactory要求返回的客户端必须继承org.apache.http.impl.client.AbstractHttpClient
  • Apache HttpClient从4.3版本开始,HttpClientBuilder.build()返回的客户端实现类是InternalHttpClient,该类不再继承AbstractHttpClient,因此触发了Groovy的类型转换异常
    关于代理配置的位置:你当前把代理写在RequestConfig里,或者用RestAssured.given().proxy()配置都可以,两种写法都有效,不是报错原因。
修复方案

推荐优先使用第一种方案,无依赖冲突问题,代码更简洁:

方案1:使用RestAssured原生的超时配置(推荐)

CoreConnectionPNames废弃后,HttpClientConfig已经提供了原生的超时配置方法,无需自定义HttpClient,直接替换原有逻辑即可:

import io.restassured.RestAssured;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.specification.RequestSpecification;

public class RequestFactory {
    private static final int TIMEOUT = 10;

    public static RequestSpecification create() {
        RestAssuredConfig config = RestAssured.config()
                .httpClient(HttpClientConfig.httpClientConfig()
                        // 原生配置连接超时
                        .setConnectionTimeout(TIMEOUT * 1000)
                        // 原生配置Socket超时
                        .setSocketTimeout(TIMEOUT * 1000));
        
        return RestAssured.given()
                .proxy("http://someurl:port")
                .config(config)
                .relaxedHTTPSValidation();
    }
}

该方案不需要额外导入Apache HttpClient的相关类,直接使用RestAssured传递的依赖即可,完全避开类型转换问题。

方案2:调整Apache HttpClient版本

如果确实需要自定义HttpClient,将Apache HttpClient和HttpCore的版本统一降到4.2.x版本即可,该版本的HttpClientBuilder.build()返回的客户端仍继承AbstractHttpClient,可兼容旧版RestAssured的类型要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:27:03