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 {
}
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
TCP(Transmission Control Protocol,传输控制协议)的历史可以追溯到1970年代初期,最初的版本是RFC 793,后来经过多次更新和改进,包括RFC 1122、RFC 1323、RFC 2018、RFC 2581、RFC 2873…