问题
I am trying to make an HTTPS REST call using Spring Integration, below is my configuration.
<int-http:outbound-gateway
id="Auth Outbound Gateway"
request-channel="RequestChannel"
request-factory="sslFactory"
header-mapper="headerMapper"
url="https://XX.XX.XX.XXX:XXXX/abcd"
http-method="POST"
expected-response-type="java.lang.String">
</int-http:outbound-gateway>
<bean id="sslFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig"
factory-method="custom">
<property name="socketTimeout" value="10000" />
<property name="connectTimeout" value="10000" />
</bean>
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder"
factory-method="create">
<property name="defaultRequestConfig" ref="requestConfig" />
</bean>
<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build" />
I am getting the following error...
javax.net.ssl.SSLException: hostname in certificate didn't match: <XX.XX.XX.XXX> != <abc.abc.xyz.com>
To solve this I wan't to AllowAllHostnameVerifier as I am calling to internal REST services.
CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
but how do I wire the above java line in my spring configuration xml?
回答1:
Custom Java
public class HttpClientFactory extends AbstractFactoryBean<HttpClient> {
@Override
public Class<?> getObjectType() {
return HttpClient.class;
}
@Override
protected HttpClient createInstance() throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
TrustStrategy allTrust = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
SSLContext sslcontext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, allTrust).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpClient;
}
}
XML Configuration
<!--SSL-->
<bean id="sslFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="httpClient" class="org.springframework.integration.samples.http.HttpClientFactory" />
回答2:
HttpClients.custom() returns a HttpClientBuilder so simply replace that builder bean and the client bean with one of your own that returns the HttpClient (after setting the defaultRequestConfig).
来源:https://stackoverflow.com/questions/34242723/allowallhostnameverifier-for-https-in-spring-integration-xml