当我使用Apache包commons-httpclient-3.1.jar时,我尝试使用以下逻辑来避免ssl认证。
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
但不幸的是,我仍然有错误:Https客户端证书身份验证错误:“javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException”
然后我选择了httpclient-4.3.3.jar,上面的逻辑也没有用,但是如果添加下面的逻辑,它就可以了。
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
httpClient是DefaultHttpClient的实例,socketfactory初始化为:
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { xtm }, null);
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
socketFactory.setHostnameVerifier(hostnameVerifier);
似乎Scheme Register是必须的。
但对于包commons-httpclient-3.1.jar,如何做方案寄存器?
提前致谢!
经过调查,以下方式可以满足要求。
Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);
EasySSLProtocolSocketFactory位于包commons-httpclient-contrib-3.1.jar中