解决httpclient 4.5 https请求跳过证书验证

来源:互联网 发布:胡金铨 知乎 编辑:程序博客网 时间:2024/05/18 18:52
public class SslUtil {public static CloseableHttpClient SslHttpClientBuild() {Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();//创建ConnectionManager,添加Connection配置信息PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();return httpClient;}private static SSLConnectionSocketFactory trustAllHttpsCertificates() {SSLConnectionSocketFactory socketFactory = null;TrustManager[] trustAllCerts = new TrustManager[1];TrustManager tm = new miTM();trustAllCerts[0] = tm;SSLContext sc = null;try {sc = SSLContext.getInstance("TLS");//sc = SSLContext.getInstance("TLS")sc.init(null, trustAllCerts, null);socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);//HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}return socketFactory;}static class miTM implements TrustManager, X509TrustManager {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkServerTrusted(X509Certificate[] certs, String authType) {//don't check}public void checkClientTrusted(X509Certificate[] certs, String authType) {//don't check}}}

原创粉丝点击