Apache HttpClient4.3.x忽略证书验证

来源:互联网 发布:ibeacon室内定位算法 编辑:程序博客网 时间:2024/06/13 09:23

今天需要忽略证书验证的时候,找了一圈没见靠谱的代码,无奈只能去官网看文档了,结果记录一下。

官方文档看这里

//此处跳过证书验证的方式适用于apache httpclient 4.3.x版本,并不一定适用于其他httpclient版本,请注意。        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustStrategy() {            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {                //信任所有                return true;            }        }).build();        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()                .register("https", sslConnectionSocketFactory)                .build();        //设置连接池,配置过期时间为20s。        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);        cm.setMaxTotal(500);        cm.setDefaultMaxPerRoute(350);        SocketConfig socketConfig = SocketConfig.custom()                .setSoKeepAlive(true)                .setTcpNoDelay(true)                .setSoTimeout(20000)                .build();        cm.setDefaultSocketConfig(socketConfig);        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000).setConnectTimeout(20000).setSocketTimeout(20000).build();        //创建httpClient        CloseableHttpClient client = HttpClients.custom()                .setConnectionManager(cm)                .setDefaultRequestConfig(requestConfig)                .build();
1 0
原创粉丝点击