cn.cliveyuan.tools.httpclient.ssl.TrustAnySSL Maven / Gradle / Ivy
The newest version!
package cn.cliveyuan.tools.httpclient.ssl;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author Clive Yuan
* @date 2021/06/08
*/
public class TrustAnySSL {
public static final X509TrustManager x509TrustManager;
public static final HostnameVerifier hostnameVerifier;
public static final SSLSocketFactory sslSocketFactory;
static {
try {
x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
hostnameVerifier = (s, sslSession) -> true;
sslSocketFactory = systemDefaultSslSocketFactory(x509TrustManager);
} catch (Throwable e) {
throw new AssertionError(e);
}
}
private static SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{trustManager}, null);
return sslContext.getSocketFactory();
}
}