HttpClient 绕过证书验证- sun.security.validator.ValidatorException: PKIX

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 问题

package com.example.demo.test;
 
import com.alibaba.fastjson2.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

@RestController
@RequestMapping(value="/hello")
public class test {

    Logger log = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/getWebServiceResult")
    public String getService() throws Exception {
        String url = "https://xxx.xx.xx:33088/csp/hsb/DHC.Published.PUB0007.BS.PUB0007.CLS?wsdl"; // WebService服务地址
        SSLContext context = createIgnoreVerifySSL();
        String data= "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:dhcc=\"http://www.dhcc.com.cn\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <dhcc:HIPMessageServer>\n" +
                "         <!--Optional:-->\n" +
                "         <dhcc:input1>?</dhcc:input1>\n" +
                "         <!--Optional:-->\n" +
                "         <dhcc:input2>?</dhcc:input2>\n" +
                "      </dhcc:HIPMessageServer>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        // String date2 = "<Request><Header><SourceSystem></SourceSystem><MessageID></MessageID></Header><Body><Content><Context>88888</Context><ActionTypeCode>4001</ActionTypeCode><FromUserRowId>2082</FromUserRowId><EpisodeId></EpisodeId><OrdItemId></OrdItemId><ToUserRowId>indoctor</ToUserRowId><OtherInfoJson> {\"\"link\"\":\"\"http://192.168.7.120:3232/#/pharmacistAdvice?hosAdmNo=0092794%26hosHospCode=1244010045535071X1\"\"}</OtherInfoJson><ToLocRowId></ToLocRowId><EffectiveDays></EffectiveDays><CreateLoc></CreateLoc></Content></Body></Request>";
 
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 自定义 SSLConnectionSocketFactory 绕过证书验证
        SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(context,
                new String[] { "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpClient = HttpClientBuilder
                .create()
                .setSSLSocketFactory(ssf)
                .setSSLHostnameVerifier((s, sslSession) -> true).build();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setSocketTimeout(6000).build();
        httpPost.setConfig(requestConfig);
        StringEntity entity = new StringEntity(data, "UTF-8");
        httpPost.setEntity(entity);
        //back为服务端返回的原始soap格式的xml数据,并且实际有用数据的“<”被转译成了“&lt;”,需要自行处理
        CloseableHttpResponse response = httpClient.execute(httpPost);
        log.info("entity1:{}", response.getStatusLine().getStatusCode());
        log.info("entity1:{}", JSON.toJSONString(response.getEntity()));
        log.info("response:{}", JSON.toJSONString(response));
//          String back=getResult(httpResponse, httpClient, httpPost);
        response.close();
        httpClient.close();
        return "back";
    }


    /**
     * 自定义证书
     * @return  /
     * @throws NoSuchAlgorithmException /
     * @throws KeyManagementException   /
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("TLS");

        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }


}

添加后测试请求
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值