使用httpClient连接https时使用服务端证书(self-signed certificate)的方法
外出旅行、冬季保暖得常备户外袜、速干袜、加厚袜子哦。 猛戳乐途驿站http://zhoupa1188.taobao.com抢购品牌男女式加厚户外袜子,coolmax、全棉、保暖、吸汗、速干、登山、徒步袜子。满10包邮 |
使用httpClient连接https时一般要在客户端引入证书。引入方法有三种:
1、在jdk中导入证书;
2、将证书路径设置到环境变量中:
System.setProperty("javax.net.ssl.trustStore", keyStore_path)
System.setProperty("javax.net.ssl.trustStorePassword", keyStore_password)3、启动java进程时将证书路径加入到启动参数中。
有时访问https网站时是不需要证书的。有时使用客户端证书不一定成功, 抛各种各样与证书相关的错误。这时可以使用服务端证书(self-signed certificate)。方法很简单,只需在httpClient调用之前先注销默认的Socket Factory,使用自定义的Socket Factory:
org.apache.commons.httpclient.protocol.Protocol.unregisterProtocol("https");
org.apache.commons.httpclient.protocol.Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 13087));
它需要依赖not-yet-commons-ssl-0.3.9.jar包:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>not-yet-commons-ssl</artifactId>
<version>0.3.9</version>
</dependency>
我遇到抛的异常为:
org.apache.axis2.AxisFault: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:83)
…
Caused by: com.ctc.wstx.exc.WstxIOException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:313)
at org.apache.axiom.om.impl.MTOMXMLStreamWriter.flush(MTOMXMLStreamWriter.java:146)
…
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
…
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:187)
…
Caused by: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:195)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:206)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:182)
… 49 more