HttpsURLConnection 显示安全警告对话框而不是捕获异常

HttpsURLConnection show Security Warning Dialog rather than catch Exception

我做了一个HttpsURLConnection如下:

        try
        {
            URL url = new URL( host );
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.connect();
            logger.debug( httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK );
        }
        catch ( Exception ex )
        {
            logger.error( ex.getMessage() );
        }

我测试的 host 没有有效的证书,所以当我在 Eclipse 中测试时,它发现 SSLHandshakeException 没问题。

但是,当我部署为 WebStart 时,它不会进入 catch 子句而是向我显示警告对话框:

如果用户点击继续,它会成功通过 connect()

我是否可以捕获异常,而不是让用户从该对话框中单击“继续”?

Java WebStart 插入自己的 SSLSocketFactory

来自https://docs.oracle.com/javase/tutorial/deployment/webstart/security.html

Dynamic Downloading of HTTPS Certificates

Java Web Start dynamically imports certificates as browsers typically do. To do this, Java Web Start sets its own https handler, using the java.protocol.handler.pkgs system properties, to initialize defaults for the SSLSocketFactory and HostnameVerifier. It sets the defaults with the methods HttpsURLConnection.setDefaultSSLSocketFactory and HttpsURLConnection.setDefaultHostnameVerifier.

If your application uses these two methods, ensure that they are invoked after the Java Web Start initializes the https handler, otherwise your custom handler will be replaced by the Java Web Start default handler.

You can ensure that your own customized SSLSocketFactory and HostnameVerifiter are used by doing one of the following:

Install your own https handler, to replace the Java Web Start https handler. In your application, invoke HttpsURLConnection.setDefaultSSLSocketFactory or HttpsURLConnection.setDefaultHostnameVerifier only after the first https URL object is created, which executes the Java Web Start https handler initialization code first.

您可以使用

在您的代码中还原
SSLContext context = SSLContext.getInstance("TLS");
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

我没有查看如何获取原始 SSLContext 的里程数,您可能需要更深入地挖掘。

要禁用对话框,请使用:

connection.setAllowUserInteraction(false);

现在如果 JVM 对证书不满意,您应该立即得到异常。