org.apache.commons.httpclient.HttpClient 出现 sun.security.provider.certpath.SunCertPathBuilderException
时间: 2023-07-22 20:30:28 浏览: 183
org.apache.commons.httpclient-3.1.jar
5星 · 资源好评率100%
这个异常通常表示 SSL 证书验证失败,可能是因为证书已过期、证书颁发机构不受信任、证书根证书不匹配等原因。
解决这个问题的方法是使用 HttpClient 的 setHostConfiguration 方法设置 SSL 相关参数,例如:
```java
HttpClient httpClient = new HttpClient();
Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
HostConfiguration config = httpClient.getHostConfiguration();
config.setHost("example.com", 443, myhttps);
```
其中,MySSLSocketFactory 是自定义的 SSL Socket 工厂类,可以根据具体情况实现其 createSocket 方法,例如:
```java
public class MySSLSocketFactory extends org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory {
@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException {
Socket socket = super.createSocket(host, port, localAddress, localPort, params);
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new MyX509TrustManager() }, null);
sslSocket.setEnabledProtocols(sslSocket.getSupportedProtocols());
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.setUseClientMode(true);
sslSocket.setNeedClientAuth(false);
sslSocket.setWantClientAuth(false);
sslSocket.setEnableSessionCreation(true);
sslSocket.startHandshake();
}
return socket;
}
}
```
MyX509TrustManager 是自定义的 X509 Trust Manager 类,可以根据具体情况实现其 checkServerTrusted 方法,例如:
```java
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// do nothing
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// do nothing
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
```
这样就可以忽略 SSL 证书验证了,但是需要注意安全风险。如果需要进行 SSL 证书验证,可以参考 HttpClient 的 SSL Guide 进行配置。
阅读全文