如何解决API调用时出现的「unable to find valid certification path」错误?
解决SSL证书错误:unable to find valid certification path to requested target
问题描述
执行代码时遇到以下错误:
Error : unable to find valid certification path to requested target
需求为访问API端点,将项目内.json文件中的JSON payload通过POST请求发送,代码如下:
package Tests; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static io.restassured.RestAssured.given; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; public class ReadJasonFile { public static void main(String[] args) throws IOException { //Credential variables String username = "MyUserName"; String password = "MyPassword"; RestAssured.baseURI = "MyBaseURI"; RequestSpecification httpRequest = RestAssured.given().auth().preemptive().basic(username, password); byte[] inp =Files.readAllBytes(Paths.get("MyFile.json")); String inputvalue = new String(inp); String response = given().header("Content-Type" , "application/json").body(inputvalue). when().post("RestOfMyEndPOintURL") .then().log().all().assertThat().statusCode(200).extract().response().asString(); } }
解决方案
1. 测试环境临时方案(禁用SSL验证)
仅适用于测试环境,生产环境严禁使用。在代码中添加SSL放松验证配置:
RestAssured.baseURI = "MyBaseURI"; // 添加此行关闭SSL证书校验 RestAssured.useRelaxedHTTPSValidation();
2. 生产环境合规方案(导入证书)
将目标API的SSL证书导入Java系统信任库,步骤如下:
- 用浏览器访问API的HTTPS地址,导出证书(保存为
.crt格式) - 执行
keytool命令导入证书到JRE信任库:
默认信任库密码为keytool -import -alias api-cert -file /你的证书路径/cert.crt -keystore $JAVA_HOME/jre/lib/security/cacertschangeit - 重启Java应用,证书即可被系统识别
代码优化提示
原代码存在两处可优化点:
- 类名
ReadJasonFile拼写错误,应为ReadJsonFile - 创建的
httpRequest未使用,导致认证信息未生效,修正后的请求代码:
String response = given() .auth().preemptive().basic(username, password) .header("Content-Type", "application/json") .body(inputvalue) .when() .post("RestOfMyEndPOintURL") .then() .log().all() .assertThat().statusCode(200) .extract().response().asString();
内容的提问来源于stack exchange,提问作者Wynand Bouwer
相关产品推荐
相关产品推荐

