本文转自:https://www.cnblogs.com/jtwbdm/p/11507121.html
当初联调某网站API(https),对方却未提供SSL证书,且一再强调无需证书,只好通过搜索网络资源设法绕过HTTPS证书验证。
原文博主的方法正好符合我的需求,转载至此以做个人记录。
正文:
调用SkipHttpsUtil.wrapClient方法获取httpclien对象,通过该对象(可强转为CloseableHttpClient)发送请求,即可跳过https证书验证。
skipHttpsUtil类
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
/**
* Description: httpclient跳过https验证
*/
public class SkipHttpsUtil {
private static Logger logger = Logger.getLogger(SkipHttpsUtil.class);
//绕过证书
public static HttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
ctx, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(ssf).build();
return httpclient;
} catch (Exception e) {
return HttpClients.createDefault();
}
}
}