Note: Advice in this article will only work for JxBrowser 6. See the corresponding article for JxBrowser 7 here.(注意:本文中的建议仅适用于JxBrowser6,JxBrowser7相应文章请点击这里。)


By default JxBrowser allows loading HTTPS web sites with invalid SSL certificates. If you need to change this default behavior and don't allow invalid SSL certificates, you can register your own LoadHandler implementation where you decide whether invalid SSL certificates should be ignored or not. For example: (默认情况下,JxBrowser允许使用无效的SSL证书加载HTTPS网站。如果您需要更改此默认行为并且不允许无效的SSL证书,则可以注册自己的LoadHandler实现,在其中确定是否应忽略无效的SSL证书。例如:)

browser.setLoadHandler(new DefaultLoadHandler() {
    @Override
    public boolean onCertificateError(CertificateErrorParams params) {
        // Return false to ignore certificate error.
        return false;
    }
});

The CertificateErrorParams parameter provides information about invalid SSL certificate. You can decide whether certificate is allowed or not using its details.(CertificateErrorParams参数提供有关无效SSL证书的信息。您可以使用其详细信息来决定是否允许使用证书。)

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Certificate;
import com.teamdev.jxbrowser.chromium.CertificateErrorParams;
import com.teamdev.jxbrowser.chromium.DefaultLoadHandler;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

/**
 * Demonstrates how to handle SSL certificate errors.
 */
public class CertificateErrorSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setLoadHandler(new DefaultLoadHandler() {
            @Override
            public boolean onCertificateError(CertificateErrorParams params) {
                Certificate certificate = params.getCertificate();
                System.out.println("subjectName = " + certificate.getSubjectName());
                System.out.println("issuerName = " + certificate.getIssuerName());
                System.out.println("hasExpired = " + certificate.hasExpired());
                System.out.println("errorCode = " + params.getCertificateError());
                // Return false to ignore certificate error.
                return false;
            }
        });
        browser.loadURL("<https-url-with-invalid-ssl-certificate>");
    }
}