无法使用java从https连接中读取内容

时间:2015-09-15 12:17:29

标签: java url ssl https

我正在尝试将使用协议HTTPS运行的url与从浏览器中获取的证书连接起来。我创建了密钥库文件并导入到JVM密钥库,但这对我不起作用。它抛出异常如下:

java.io.IOException: Server returned HTTP response code: 401 for URL: https://TRIED_URL
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at TestURLConnection.getSSLConnection(TestURLConnection.java:145)
    at TestURLConnection.main(TestURLConnection.java:106)

以下是我尝试的代码。

public static void getSSLConnection() {

        try {
            String jkspath = "C://Users//myuser//Desktop//clientkeystore"
                    ,jkspass="jkspassword",proxy = "proxy.com", port = "8080";

            URL url = new URL("https://TRIED_URL");

            Properties systemProperties = System.getProperties();
            systemProperties.setProperty("http.proxyHost", proxy);
            systemProperties.setProperty("http.proxyPort", port);
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username",
                            "password".toCharArray());
                }
            });
            HttpsURLConnection urlConnection = (HttpsURLConnection) url
                    .openConnection();
            // Load Trusted Certs into a KeyStore Object
            KeyStore ksCACert = KeyStore.getInstance(KeyStore.getDefaultType());
            ksCACert.load(new FileInputStream(jkspath),
                    jkspass.toCharArray());
            // Initialise a TrustManagerFactory with the CA keyStore
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(ksCACert);
            // Create new SSLContext using our new TrustManagerFactory
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
            // Get a SSLSocketFactory from our SSLContext
            SSLSocketFactory sslSocketFactory = context.getSocketFactory();
            // Set our custom SSLSocketFactory to be used by our
            // HttpsURLConnection instance
            urlConnection.setSSLSocketFactory(sslSocketFactory);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

请帮我解决这个问题。

谢谢

0 个答案:

没有答案