根据这个 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);
}
}