How to Create a Spring RestTemplate using HttpClient5
https://www.czetsuyatech.com/2023/03/spring-rest-resttemplate-using-httpclient5.html
Overview
The RestTemplate serves as the primary Spring class for HTTP access on the client side. It operates on a comparable conceptual level to other templates such as JdbcTemplate, JmsTemplate, and those featured in other Spring Framework and portfolio projects.
Code
@Bean
public RestTemplate restTemplate() throws Exception {
char[] password = "ca_pass_123".toCharArray();
SSLContext sslContext = SSLContextBuilder.create()
.loadKeyMaterial(keyStore("classpath:truststore.p12", password), password)
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslContext)
.build();
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslSocketFactory)
.setDefaultTlsConfig(TlsConfig.custom()
.setHandshakeTimeout(Timeout.ofSeconds(30))
.setSupportedProtocols(TLS.V_1_3)
.build())
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}
private KeyStore keyStore(String file, char[] password) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KEY_TYPE);
File key = ResourceUtils.getFile(file);
try (InputStream in = new FileInputStream(key)) {
keyStore.load(in, password);
}
return keyStore;
}




Post a Comment