且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式添加自签名证书以从Java代码发出HTTPS请求?

更新时间:2023-01-11 08:40:40

You can configure the HttpsURLConnection socket factory to accept all certificate without any validation:

private class TrustAll implements X509TrustManager
{
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public X509Certificate[] getAcceptedIssuers()
    {
        return new X509Certificate[0];
    }
}

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { new TrustAll() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

UPDATE

You just have to call this code once at the start of the application. All HTTPS connections opened with URL.openConnection() will use this socket factory. Another solution could be adding this code in the createSSLSocket() method body.