• Java httpclient.CloseableHttpClient跳过https证书验证


    本文转自: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();
            }
        }    
    }

  • 相关阅读:
    Python基础 | pandas中dataframe的整合与形变(merge & reshape)
    Python基础 | pandas中数据的筛选(index & subset)
    Python基础 | 关于“循环”那些事
    Python基础 | 数据文件的读写
    Python基础 | 字符串操作
    如何用数据说谎 How to lie with data
    浅谈“数据敏感度”
    爬虫 | IT桔子互联网公司死亡名单
    从一道面试题谈数据推算方法
    爬虫 | cnblog文章收藏排行榜(“热门文摘”)
  • 原文地址:https://www.cnblogs.com/yan-zm/p/11896856.html
Copyright © 2020-2023  润新知