报错PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to f

本文介绍了一种在调用第三方HTTPS接口时遇到证书验证错误的解决方法,提供了通过代码忽略证书验证的示例,适用于需要快速解决HTTPS调用问题的开发者。

原文地址:https://www.cnblogs.com/lkeji388/p/9677464.html

 

今天在调用第三方HTTPS接口的时候,一直显示这个报错,然后百度很久,有2种解决方法,一个是说自己手动去导入,第二种用代码忽略证书验证。我用二种方式,

复制即用,

 

public void test2() throws Exception {

        Map<String,Object> map=new LinkedHashMap<>();
        map.put("teletephone",手机号码);
        map.put("msgCode",车牌号);
        map.put("msgContent",地址);
        List<Map<String,Object>> list=new ArrayList<>();
        list.add(map);
        String params= JSONArray.toJSONString(list);
        System.out.println(params);
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(params.getBytes());//编码
        System.out.println(encode);

        URL console = new URL("第三方路径?method=sendMSGPublic&id=1&params="+params);
        HttpURLConnection conn = (HttpURLConnection) console.openConnection();
        if (conn instanceof HttpsURLConnection)  {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
            ((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier());
        }
        conn.connect();
        System.out.println(conn.getResponseCode());
        if(200 == conn.getResponseCode()){
            //得到输入流
            InputStream is =conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while(-1 != (len = is.read(buffer))){
                baos.write(buffer,0,len);
                baos.flush();
            }
            System.out.println(baos.toString("utf-8"));
        }
    }

    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }


    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值