JavaFX WebView 无法使用不受信任的 SSL 证书工作

nac*_*ch0 4 java ssl https javafx certificate

我正在使用 JavaFX 开发一个简单的嵌入式浏览器:

final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
Run Code Online (Sandbox Code Playgroud)

当我webEngine用来加载任何 http 网站时,它工作正常:

webEngine.load("http://google.es");
Run Code Online (Sandbox Code Playgroud)

尽管如此,如果我尝试使用不受信任的证书(我自己的 ssl 证书)加载网站,webEngine则不起作用,并且我在浏览器中出现白屏。

有没有办法(自动)信任我的 ssl 证书?

nac*_*ch0 5

最后,我解决了我的问题。您应该在加载网站之前添加此代码:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
}; 

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL"); 
    sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
} 
// Now you can access an https URL without having the certificate in the truststore
try { 
    URL url = new URL("https://hostname/index.html"); 
} catch (MalformedURLException e) {
} 
//now you can load the content:

webEngine.load("https://example.com");
Run Code Online (Sandbox Code Playgroud)

注意: 此代码片段只是禁用证书验证,不信任它。