簡體   English   中英

在HttpURLConnection中容納HTTPS連接

[英]Accommodate HTTPS Connections in HttpURLConnection

我正在使用HttpURLConnection進行POST請求。

我讀了HttpsURLConnection擴展了HttpURLConnection並支持https特定功能(例如SSL)

如果HttpsURLConnection在HttpURLConnection(父類)中使用相同的方法,則它將從HttpURLConnection超級調用這些方法。

        URL url = new URL(callBackUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(setConnectTimeout);
        connection.setReadTimeout(setConnectTimeout);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
        os.write(data.toString());

        os.flush();
        os.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));

            while ((output = br.readLine()) != null) {
                stringBuffer.append(output);

            }
        }

但是,當我使用HTTPS網址時,我不斷收到以下錯誤;

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.8.0_181]
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1964) ~[na:1.8.0_181]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:328) ~[na:1.8.0_181]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:322) ~[na:1.8.0_181]

問題,我如何處理SSL和非SSL連接,就像在PHP中那樣,當使用CURL時,您設置了忽略SSL檢查

curl_setopt($cHandler, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($cHandler, CURLOPT_SSL_VERIFYPEER, true);

我在Linux,Spring框架和TomCat Web服務器上。

任何人?

為了使HTTPS能夠首先運行,您需要將SSL證書添加到Java的信任庫中。為此,您必須執行以下步驟:

通常,使用的JVM的信任庫文件將位於%JAVA_HOME%\\lib\\security\\cacerts

您可能首先通過運行以下命令來查看您的證書是否已經添加到信任庫中:

keytool -list -keystore "%JAVA_HOME%/jre/lib/security/cacerts"

一旦確認未將其添加到Java信任庫中,就可以使用以下命令將其添加:

keytool -import -noprompt -trustcacerts -alias <AliasName> -file   <certificate> -keystore <KeystoreFile> -storepass <Password>

完成以下步驟后,您應該能夠運行程序,而不會遇到與HTTPS相關的問題。

希望有幫助!

EDIT-1 :以上方法有助於在Windows環境中添加SSL證書。 請查看以下有關Linux變體的文章 ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM