Solve the PKIX path building fail of HttpClient request https

Preface

The recently used Abuyun’s java dynamic proxy ip code test found that when the request does not trust https, a PKIX path building fail exception will occur . Check information because of https certificate issue.

Program

  • Importing the corresponding trust certificate is a feasible solution, but if you need to crawl a lot of websites, you need to import more than one, so it is not used. But I think it is better to import the certificate for a single fixed one.
  • Use ignore certificate request. The specific implementation is as follows:

achieve

1. Obtaining the most basic HttpClient ignores the certificate

/**  
* @Title: HttpUtils.java  
* @Package com.zl.vtax.util  
* @Description: TODO(用一句话描述该文件做什么)  
* @author DRJYY  
* @date 2019年7月3日  
* @version V1.0  
*/
package com.zl.vtax.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.log4j.Logger;

/**
 * @ClassName: HttpUtils.java
 * @Description: TODO(获取忽略证书的HttpClient)
 * @author drj
 * @date 2019年7月3日 下午5:44:26
 * @version V1.0
 */
public class HttpUtils {

    private static Logger logger = Logger.getLogger(HttpUtil.class);

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有证书
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }

            }).build();
            SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslFactory).build();
        } catch (Exception e) {
            logger.error("处理Https证书异常", e);
        }
        return HttpClients.createDefault();
    }
}

Guess you like

Origin blog.csdn.net/qq_29897369/article/details/94666748