Ric*_*ick 7 java ssl https httpclient
我在尝试使用HttpClient来调用使用自签名证书的https站点时感到有点困惑.我有下面的代码,这使我能够进行调用,但后来我得到的错误就像javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found
我从我的网络浏览器下载了证书并了解我可以将其导入密钥库但我宁愿把它放入代码并以这种方式使用它,有没有办法做到这一点?
HttpClient client = new HttpClient();
EasySSLProtocolSocketFactory easySSLProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol https = new Protocol("https", easySSLProtocolSocketFactory,
443);
Protocol.registerProtocol("https", https);
BufferedReader br = null;
String responseString = "";
GetMethod method = new GetMethod(path);
int returnCode = client.executeMethod(method);
Run Code Online (Sandbox Code Playgroud)
假设您的证书是 PEM 格式。您可以将其嵌入代码中并使用BouncyCastle将PEMReader
其转换为X509Certificate
实例。完成此操作后,KeyStore
在内存中创建一个实例并将此 X.509 证书放入其中。然后,SSLContext
使用它KeyStore
作为信任存储来实例化一个新的,并让您的 HTTP 客户端使用它。
这看起来像这样(没有尝试过,记得关闭读者并捕获异常......):
PEMReader pemReader = new PEMReader(new StringReader("----- BEGIN ......");
X509Certificate cert = (X509Certificate) pemReader.readObject();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("some name", cert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tmf.getTrustManagers(), null);
Run Code Online (Sandbox Code Playgroud)
然后,使用它SSLContext
进行连接。如果您使用的是 4.x 版本,则可以使用 Apache HttpClient 的SSLSocketFactory来执行此操作(如果您使用的是 3.x 版本,则可以使用此方法)。我建议现在使用 Apache HttpClient 4.x。
归档时间: |
|
查看次数: |
13054 次 |
最近记录: |