在Java的编程世界里面,我们有的时候,会经常访问一些HTTPS的网站,那么访问这些HTTPS的网站的时候,如果当前这个网站是自己企业内部的已知 的网站,或者我们信任的网站,这个时候,我们为了编写程序的方便,就不需要把当前网站的服务器的根证书以及中间证书导入到JKS里面,让在程序在调用HTTP协议的时候对服务器的服务器名和证书名进行对比
---------------------
把下面这段代码加入到类中
static {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier
(
(urlHostName, session) -> true
);
} catch (Exception e) {
}
}
private static void trustAllHttpsCertificates()
throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
private static class TrustAllManager
implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
}