import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Value("${http.client.ssl.key-store}")
private Resource keyStore;
@Value("${http.client.ssl.trust-store}")
private Resource trustStore;
@Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;
private RestTemplate getRestTemplate() {
try {
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(
keyStore.getFile(),
// pass twice, for key-store AND certificate:
keyStorePassword.toCharArray(),
keyStorePassword.toCharArray())
.loadTrustMaterial(
trustStore.getURL(),
keyStorePassword.toCharArray(),
// use this for self-signed certificates only:
new TrustSelfSignedStrategy())
.build();
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()))
.build();
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
} catch (IOException
| NoSuchAlgorithmException
| KeyStoreException
| UnrecoverableKeyException
| CertificateException
| KeyManagementException e) {
throw new RuntimeException(e);
}
}
// ...
RestTemplate restTemplate = getRestTemplate();
String url = https://example.com:8443/some/where/{myParam}
MyObject myObject = restTemplate.getForObject(url, MyObject.class, Maps.newHashMap("myParam", 42));