HttpURLConnection绕过SSL验证,信任所有证书的工具类
发起https请求时经常会出现javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException
这样的错误,那是因为环境中没有证书校验,我们可以在连接中设置绕过SSL校验来解决这个问题。
public class SslUtil {
// 针对全局
public 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());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
}
// 针对单个连接
public static void trustAllHttpsCertificates(URLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
httpsURLConnection.setSSLSocketFactory(sc.getSocketFactory());
httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
}
private static class TrustAllManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
}
}
标签:trustAllCerts,Override,证书,SSL,sc,new,null,public,HttpURLConnection
From: https://blog.51cto.com/u_16167766/6715904