package com.common.utils;
import javax.annotation.Nullable;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
public class HttpsUtils {
/**
* 设置单个连接的SSL 实例类型
* @param connection 连接
* @param instance 实例类型 TLSv1, TLSv2, SSL
*/
public static void setSSLContext(HttpURLConnection connection, String instance) {
if (connection instanceof HttpsURLConnection) {
setSslContext((HttpsURLConnection) connection, instance);
}
}
/**
* 设置单个连接的SSL 实例类型
* @param connection https 连接
* @param instance 实例类型 TLSv1, TLSv2, SSL
*/
public static void setSslContext(HttpsURLConnection connection, String instance) {
try {
connection.setSSLSocketFactory(buildSslFactory(instance));
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
private static SSLSocketFactory buildSslFactory(String instance) throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance(instance);
sc.init(null, trustAllCerts, null);
return sc.getSocketFactory();
}
/**
* 设置全局默认SSL 实例类型
* @param instance 实例类型
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static void setDefaultTrustAllHttpsCertificates(@Nullable String instance) throws NoSuchAlgorithmException, KeyManagementException {
instance = instance == null ? "SSL" : instance;
HttpsURLConnection.setDefaultHostnameVerifier((str, session) -> true);
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance(instance);
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
}
注意:本文归作者所有,未经作者允许,不得转载