我正在使用apache httpclient 4.5.3和apache httpcore 4.4.6。我需要通过POST调用来调用SOAP WS
他们给了我一张pfx证书。我通过配置SOAP UI在SOAP UI中使用它,所有工作都非常好。我可以调用WS,它给了我一个响应。证书有效
现在我正在尝试配置apache httpclient来做同样的事情。这里是我写的代码:
KeyStore clientStore = KeyStore.getInstance("PKCS12");
InputStream instream = Thread.currentThread().getContextClassLoader().getResourceAsStream(keystoreName);
try {
clientStore.load(instream, keyStorePwd.toCharArray());
} finally {
instream.close();
}
SSLContext sslCtx = SSLContext.getDefault();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslCtx);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionFactory).register("http", new PlainConnectionSocketFactory()).build();
PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(registry);
HttpClientBuilder hcb = HttpClientBuilder.create();
hcb.setConnectionManager(pcm);
CloseableHttpClient httpClient = hcb.build();
通过尝试此代码,我无法成功调用WS。我确定我错过了一些东西,但我找不到我错过的东西
愿任何人建议我如何继续吗?
谢谢 安吉洛
答案 0 :(得分:3)
我想到了我所缺少的东西。我在这里发布我的解决方案,希望它可以是有用的
基本上我错了,因为我没有仔细配置SSLContext 我必须仔细配置它。
这就是我写的:
KeyStore clientStore = KeyStore.getInstance("PKCS12");
InputStream instream = Thread.currentThread().getContextClassLoader().getResourceAsStream(keystoreName);
try {
clientStore.load(instream, keyStorePwd.toCharArray());
} finally {
instream.close();
}
//Trust everybody
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}
};
SSLContext sslCtx = SSLContext.getInstance("TLS");
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(clientStore, keyStorePwd != null ? keyStorePwd.toCharArray() : null);
KeyManager[] keymanagers = kmfactory.getKeyManagers();
sslCtx.init(keymanagers, new TrustManager[]{tm}, null);
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslCtx);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionFactory).register("http", new PlainConnectionSocketFactory()).build();
PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(registry);
HttpClientBuilder hcb = HttpClientBuilder.create();
hcb.setConnectionManager(pcm);
CloseableHttpClient httpClient = hcb.build();
现在一切都很好
谢谢
安吉洛