忽略HTTPS SSL校验

我们在使用httpclien请求https接口时,目标站点启用了HTTPS 而缺少安全证书时出现的异常 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 这是我们可以找到该站点的证书加入到信任库,或者忽略该验证,下面是忽略该验证方法

  • apache的HTTPClient



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.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 使用此httpclient可以忽略HTTPS的SSL证书校验
 */
public class SSLHttpClient extends DefaultHttpClient {
    public SSLHttpClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, getTrustingManager(), null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }

    private static TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        return trustAllCerts;
    }
}

然后使用该httpclient进行http请求


        SSLHttpClient httpClient = null;
        // 创建Post请求
        HttpPost httpPost = null;
        try {
            httpClient = new SSLHttpClient();
            httpPost = new HttpPost(webServiceURL);
            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectTimeout).build();
            httpPost.setConfig(requestConfig);
            // 设置Post请求报文头部
            httpPost.setHeader("Content-Type", soap);
            httpPost.setHeader("SOAPAction", soapAction);
            // 添加报文内容
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                return EntityUtils.toString(httpEntity, "UTF-8");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpClient!=null){
                httpClient.close();
            }
        }
        return null;
  • hutool的HttpUtil设置忽略SSL
/**
 * @author cf
 * @date 2023/7/3下午 1:06
 */
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLUtils {
    /**
     * 忽略https证书验证
     * @return
     */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    //检查客户端证书,若不信任该证书抛出异常,咱们自己就是客户端不用检查
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
                    //检查服务器的证书,若不信任该证书抛出异常,可以不检查默认都信任
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
                    //返回受信任的X509证书数组
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }
}

进行调用

import cn.hutool.http.HttpRequest;
/**
 * cf
 */
public class TqOdpServiceClient {

     private static String url="url";;
     public static String execute(String http,String params,String auth) {
         String result2 = HttpRequest.post(http+url)
                 .header("Authorization", auth)
                 .header("Content-Type", "application/json;charset=UTF-8").setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
                 .body(params)
                 .execute().body();
         return result2;
     }
}
全部评论

相关推荐

2025-11-11 16:40
已编辑
门头沟学院 人工智能
不知道怎么取名字_:这个有点不合理了,相当于已经毕业了,但还是没转正,这不就是白嫖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务