import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* @author
*
*/
public class MyX509TrustManager implements 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 null;
}
/**
* 測試
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String urlString = "";
URL url = new URL(urlString);
HttpsURLConnection httpsConn =
(HttpsURLConnection) url.openConnection();
TrustManager[] tm = {new MyX509TrustManager()};
// 建立 SSLContext
SSLContext sc = SSLContext.getInstance("TLSv1.2");
// 初始化 SSLContext
sc.init(null, tm, new java.security.SecureRandom());
// 獲取 SSLSocketFactory 物件
SSLSocketFactory ssf = sc.getSocketFactory();
// 設定當前使用的 SSLSoctetFactory
httpsConn.setSSLSocketFactory(ssf);
}
}