Skip to content

Instantly share code, notes, and snippets.

@donhenton
Last active September 1, 2020 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donhenton/0f083a69b9c323198d111af29ba09687 to your computer and use it in GitHub Desktop.
Save donhenton/0f083a69b9c323198d111af29ba09687 to your computer and use it in GitHub Desktop.
create a Resttemplate that can handle a self signed cert
/**
* note that in spring boot resource filtering must be turned OFF or file will be altered
* https://gist.github.com/jonashackt/aae3ba2cb5595bb0f56550e604522ea6
* https://raymondhlee.wordpress.com/2016/01/09/setup-spring-resttemplate-to-accept-self-signed-cert/
*/
private HttpClient createHttpClient() {
SSLConnectionSocketFactory socketFactory = null;
try {
SSLContext ctn = SSLContextBuilder
.create()
.loadKeyMaterial(ResourceUtils.getFile("classpath:cacerts.jks"), "changeit".toCharArray(), "changeit".toCharArray())
.loadTrustMaterial(ResourceUtils.getFile("classpath:cacerts.jks"), "changeit".toCharArray(), new TrustSelfSignedStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
return true;
}
})
.build();
socketFactory
= new SSLConnectionSocketFactory(ctn);
} catch ( IOException | KeyManagementException | KeyStoreException |
NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException t) {
throw new RuntimeException(t.getClass().getName() + " " + t.getMessage());
}
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
}
/**
* This method gets the Rest Template with required configuration
*
* @return restTemplate
*/
public RestTemplate getRestTemplate() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(this.createHttpClient());
requestFactory.setConnectTimeout(Integer.parseInt(Constants.CONNECTION_TIMEOUT));
requestFactory.setReadTimeout(Integer.parseInt(Constants.RECEIVE_TIMEOUT));
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse arg0) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse arg0) throws IOException {
//
}
});
return restTemplate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment