【发布时间】:2014-03-08 12:38:06
【问题描述】:
我需要忽略 Java 中的所有 SSL 证书,但我一辈子都无法让它工作。我已经浏览了下面列出的以下页面,但似乎每个 https 链接都不起作用。
stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
stackoverflow.com/questions/13470998/ignoring-ssl-validation-in-java
stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java
stackoverflow.com/questions/2694281/ignore-certificate-errors-when-requesting-a-url-in-java
stackoverflow.com/questions/6681969/java-ignore-certificate-validation
www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/
code.google.com/p/misc-utils/wiki/JavaHttpsUrl
www.exampledepot.8waytrips.com/egs/javax.net.ssl/TrustAll.html
www.obsidianscheduler.com/blog/ignoring-self-signed-certificates-in-java/
java.dzone.com/articles/how-ignore-cert-and-host-name
gist.github.com/henrik242/1510165
我有充分的理由需要这样做,所以不用担心,但我确实需要能够做到。基本上,我需要查看内部 https 链接列表并检查以确保它们仍然有效并且没有损坏的链接。一些链接工作正常,因为 Java 代码忽略了证书并且可以返回 HTTP 响应标头,但其他链接即使在我的 Web 浏览器中工作正常也会超时。所有这些链接都是公司内部链接。
我尝试过使用 HttpsURLConnection 以及 HttpGet 和 HttpClient。是否有其他我没有想到的东西,或者与 Java 无关的东西可能导致页面超时?我只是想确保链接的 URL 存在。以下是我遇到的例外情况。
使用 HttpGet/SSLContextBuilder/PoolingHttpClientConnectionManager:
org.apache.http.conn.HttpHostConnectException: Connect to -removed- [-removed-] failed: Connection timed out: connect
通过 HttpsUrlConnection 使用 X509TrustManager:
java.net.ConnectException: Connection timed out: connect
具体来说,我根据上面发布的链接尝试了以下方法及其许多变体:
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
javax.net.ssl.SSLContext sc = null;
try {
sc = javax.net.ssl.SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
我也尝试过这个以及几个变体:https://stackoverflow.com/a/19950935/1727920
【问题讨论】: