首页 文章

Java Unirest禁用证书

提问于
浏览
2

你可以告诉我如何禁用证书验证使用Unirest作为休息客户端 .

我使用Unirest和Java Spring . 以下是我的源代码:

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:无法找到所请求目标的有效证书路径

1 回答

  • 0

    在触发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类型,而不是String .

相关问题