Java Unirest 禁用证书验证

3

请问怎样禁用证书验证以便使用Unirest作为REST客户端。

我正在使用Java Spring来使用Unirest。以下是我的源代码:

try {
    HttpResponse<String> response = Unirest.post("myurl")
      .header("content-type", "application/json")
      .header("accept", "application/json")
      .body("my json data here")
      .asJson();
} catch (Exception e) {
    logger.info("==================REST CLIENT ERROR: "+e.getMessage());
}

结果:

==================REST客户端错误:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:PKIX路径构建失败: sun.security.provider.certpath.SunCertPathBuilderException:无法 找到请求目标的有效认证路径

(注意:翻译只是根据字面意思进行的,可能不够准确。)
3个回答

5

我知道这个讨论串很老了,但只是为了写下一个更简单的方法,以便其他人能够找到。

现在Unirest已经内置了对此的支持。

Unirest.config().verifySsl(false);

这对我有用。


感谢您快速的调整。 - Usman Liaqat

3

在触发http post请求之前,按照以下方式设置自定义的http客户端到Unirest中:

try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        HttpClient customHttpClient = HttpClients.custom().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        Unirest.setHttpClient(customHttpClient);
        HttpResponse<JsonNode> response = Unirest.post("myurl")
                .header("content-type", "application/json")
                .header("accept", "application/json")
                .body("my json data here")
                .asJson();
    } catch (Exception e) {
        logger.info("==================REST CLIENT ERROR: " + e.getMessage());
    }

顺便提一下,要注意的是asJson方法返回的是JsonNode类型,而不是字符串。


这看起来像是忽略了SSL验证,是吗? - tiennv

2
使用此选项将验证 SSL 设置为 false。
Unirest.config().verifySsl(false)

注意:如果您正在使用com.mashape.unirest库v1.4.9,则不会在其中找到config()方法。
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>

我切换到kong.unitrestjava,并且它有本地的config()方法可以将verifySsl设置为false。
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.11.13</version>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接