Monday, 2 March 2020

RestTemplate: Disable ssl certificate validation

Following snippet return RestTemplate instance which ignores SSL certificate validation.

public RestTemplate getRestTemplate() throws BaseException {

 try {
  TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
   @Override
   public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    return true;
   }
  };
  SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
    .loadTrustMaterial(null, acceptingTrustStrategy).build();
  SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
  CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
  HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
  requestFactory.setHttpClient(httpClient);
  RestTemplate restTemplate = new RestTemplate(requestFactory);
  return restTemplate;
 } catch (Exception e) {
  e.printStackTrace();
 }

}


Previous                                                    Next                                                    Home

No comments:

Post a Comment