報錯PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"


今天在調用第三方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;
        }


    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM