【问题标题】:Java Unirest disable cerificateJava Unirest 禁用证书
【发布时间】:2018-07-12 19:29:45
【问题描述】:

您能否告诉我使用 Unirest 作为 REST 客户端禁用证书验证的方法。

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

【问题讨论】:

    标签: java spring spring-boot unirest


    【解决方案1】:

    使用它来设置验证 ssl 为假

    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>
    

    【讨论】:

      【解决方案2】:

      我知道这个帖子很老了,但只是写以防万一其他人正在寻找更简单的方法。

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

      Unirest.config().verifySsl(false);

      这对我有用。

      【讨论】:

      • 感谢您的快速调整。
      【解决方案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 类型,而不是 String。

      【讨论】:

      • 这看起来像是忽略所有 SSL 验证,不是吗?
      猜你喜欢
      • 2014-06-08
      • 2018-11-11
      • 2019-06-28
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      相关资源
      最近更新 更多