忽略Java的SSL证书错误
Apache Http客户端。您可以在此处查看相关代码:
String url = "https://path/to/url/service";HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
// Test whether to ignore cert errors
if (ignoreCertErrors){
  TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager(){
      public X509Certificate[] getAcceptedIssuers(){ return null; }
      public void checkClientTrusted(X509Certificate[] certs, String authType) {}
      public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }
  };
  try {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
  } catch (Exception e){
    e.printStackTrace();
  }
}
try {
  // Execute the method (Post) and set the results to the responseBodyAsString()
  int statusCode = client.executeMethod(method);
  resultsBody = method.getResponseBodyAsString();
} catch (HttpException e){
  e.printStackTrace();
} catch (IOException e){
  e.printStackTrace();
} finally {
  method.releaseConnection();
}
这是每个人都用来忽略SSL证书错误的方法(仅将其设置为登台,它将不会在生产中使用)。但是,我仍然收到以下异常/堆栈跟踪:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building unable to find valid certification path to requested target任何提示都很好。如果我做的TrustManager错误,或者我应该以不同的方式执行HTTP Post方法,则可以选择两种方式。
谢谢!
回答:
首先,不要 忽略 证书错误。与他们打交道。忽略证书错误将打开与潜在MITM攻击的连接。这就像关闭烟雾报警器中的蜂鸣器一样,因为有时它会发出声音…
可以肯定的是,它仅用于测试代码,不会最终投入生产,但是我们都知道截止日期临近时会发生什么:测试代码不会显示任何错误->我们可以发货照原样。如果需要,应改为设置测试CA。制作起来并不难,而且整个过程当然也不会比引入自定义代码进行开发并将其从生产环境中删除更为困难。
您显然正在使用Apache Http Client:
HttpClient client = new HttpClient();int statusCode = client.executeMethod(method);
但是,您正在javax.net.ssl.HttpsURLConnection使用SSLContext创建的进行初始化:
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());这完全独立于Apache Http Client设置。
相反,您应SSLContext按照此答案中的说明为ApacheHttp Client库设置。如果您使用的是Apache Http Client
3.x,则需要自行设置SecureProtocolSocketFactory才能使用它SSLContext(请参阅此处的示例)。值得升级到Apache
Http Client 4.x,它直接支持SSLContext。
您也可以使用Pascal的答案正确导入证书。同样,如果您遵循该问题接受的答案(由Kevin回答),则您确实会忽略该错误,但这会使连接容易受到MITM攻击。
以上是 忽略Java的SSL证书错误 的全部内容, 来源链接: utcz.com/qa/401080.html







