javax.net.ssl.SSLHandshakeException: PKIX path building failed

在連遠端的 https ,由於是自signed 憑證或憑證的驗證上有出問題,java 程式會卡關。解法,增加一個 function 來略過憑證,範例程式碼如下:

public static String getBase64FromUrl(String fileUrl) {
    InputStream inputStream = null;
    byte[] data = null;
    ByteArrayOutputStream swapStream = null;
    HttpsURLConnection conn = null;
    try {
        URL url = new URL(fileUrl);
        if (fileUrl.contains("https:")){
            SSLContext context = createIgnoreVerifySSL();
            createIgnoreVerifySSL();
            conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(context.getSocketFactory());
            inputStream = conn.getInputStream();
        }else {
            inputStream =  url.openConnection().getInputStream();
        }

        swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        data = swapStream.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(swapStream);
    }
    return new String(Base64.encodeBase64(data));
}

public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sc = SSLContext.getInstance("TLS");
    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;
}

HttpsURLConnection 好像不能輸入 url 是 “http” 的樣子,可以遇到 http 改用 HttpURLConnection class 即可。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *