1.使用HttpURLConnection发送请求
private static void trustAllCertificates(HttpURLConnection con) throws NoSuchAlgorithmException, KeyManagementException {
((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
// Ignore Certification
TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
((HttpsURLConnection) con).setSSLSocketFactory(ssf);
}
在发送请求时,在HttpURLConnection声明后调用上述方法,如下:
HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
trustAllCertificates(connection);
2.使用HttpClient 发送请求
public static HttpClient create() throws KeyManagementException, NoSuchAlgorithmException {
// 创建一个信任所有证书的TrustManager
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// 初始化SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new SecureRandom());
// 创建使用我们SSLContext的SSLConnectionSocketFactory
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// 创建配置了我们SSLConnectionSocketFactory的HttpClient
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build();
return httpClient;
}
调用时如下,用上述方法声明 HttpClient即可:
HttpClient httpClient = create();
或者
CloseableHttpClient httpClient = (CloseableHttpClient)create();