2017-06-12 143 views
0

我使用apache httpclient 4.5.3和apache httpcore 4.4.6。我需要通過POST調用來調用SOAP WSapache httpclient pfx文件

他們給了我一個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

我想我錯過了什麼。我發佈我的解決方案希望它可以是有用的

基本上我錯了,因爲我沒有仔細配置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(); 

現在所有的作品不錯

謝謝

安傑洛