如何从WebConversationWebRequest对象的上下文中忽略SSL证书问题?我知道我可以创建一个伪造的TrustManager来接受所有证书,但是如何在HttpUnit上下文中设置呢?

这是我得到的例外:

[Security:090508]Certificate chain received from my.domain.com - NUM.NUM.NUM.NUM was incomplete.,
[Security:090477]Certificate chain received from my.domain.com - NUM.NUM.NUM.NUM was not trusted causing SSL handshake failure.


我需要以某种方式将SSLSocket设置设置为WebConversation或WebRequest对象;查看HttpUnit的JavaDocs,没有这样的方法或构造函数。有什么办法可以将其包装在某些具有SSLSocket属性的对象中?

最佳答案

根据this FAQ entry,看来HttpUnit正在使用Java标准库提供的SSL实现。编写和安装“全部接受” TrustManager很简单:

private static class AnyTrustManager implements X509TrustManager
{
    public void checkClientTrusted(X509Certificate[] chain, String authType)
    {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
    {
    }

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

static {
    try {
        SSLContext ssl = SSLContext.getInstance("SSL");
        ssl.init(null, new X509TrustManager[] {new AnyTrustManager()}, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
    } catch (NoSuchAlgorithmException ex) {
        throw new Error(ex);
    } catch (KeyManagementException ex) {
        throw new Error(ex);
    }
}


但是,请记住,此代码示例可能需要进行一些修改才能与HttpUnit一起使用(例如,如果库使用自定义SocketFactory建立连接)

由于HttpUnit似乎没有提供任何API来设置自定义SSLSocketFactry,因此这里是设置默认SSL上下文的替代解决方案(仅Java 6)

static {
    try {
        SSLContext ssl = SSLContext.getDefault();
        ssl.init(null, new X509TrustManager[] {new AnyTrustManager()}, null);
    } catch (NoSuchAlgorithmException ex) {
        throw new Error(ex);
    } catch (KeyManagementException ex) {
        throw new Error(ex);
    }
}

09-13 06:43