jsp如何打开随机https url?

时间:2018-04-30 16:17:08

标签: java jsp ssl

我想阅读用户输入的https网址内容,我们没有关于证书密钥和jks等的任何数据:

<!DOCTYPE html>
<html>
<head>
    <title>Total Synthesis of Fidaxomicin |  | download</title>
</head>
<body>
    <form action="testSSL.jsp">
        <input name="sslRandomUrl" type="text">
        <input type="submit" value="opensslUrl" >
    </form>
</body>

这是jsp:

<%@page import="java.net.URL"%>
<%@page import="javax.net.ssl.HttpsURLConnection"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

    <%
        String url = request.getParameter("sslRandomUrl");
        System.out.println("How to open like web browser? >>>"+url);
        URL pdfContainerUrl = new URL(url);
        HttpsURLConnection conn2 = (HttpsURLConnection) pdfContainerUrl.openConnection();// دقت شود https 
        StringBuilder result = new StringBuilder();
        conn2.setRequestMethod("GET");
        BufferedReader br2 = new BufferedReader(new InputStreamReader(conn2.getInputStream(), "UTF-8"));
        String line2;
        while ((line2 = br2.readLine()) != null) {
            result.append(line2);
            System.out.println(line2);
        }
        out.print(result);
    %>

但是我对很多网址都有这个错误:

  

ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径

如何强制jdk打开所有https网址?

1 个答案:

答案 0 :(得分:1)

您可以尝试在JSP中插入它:

    /* Start of Fix */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }

    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) { return true; }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /* End of the fix*/

来源:How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?