I have created the following configuration class in order to trust all certificates in my spring boot project:
package com.nttdata.iplanet.hubject.utils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
@Configuration
public class TrustAllCertificatesConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder()
.requestFactory(this::trustAllCertificatesRequestFactory)
.build();
}
private ClientHttpRequestFactory trustAllCertificatesRequestFactory() {
TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Failed to initialize SSLContext", e);
}
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
// Utilizzare una versione di HttpComponentsClientHttpRequestFactory compatibile
// con la versione delle librerie Apache HTTP Client che stai utilizzando.
// Versione per Apache HTTP Client 4.5.x:
// return new HttpComponentsClientHttpRequestFactory(httpClient);
// Versione per Apache HTTP Client 4.3.x:
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
}
But I receive error in the last raw of my code, that is:
return new HttpComponentsClientHttpRequestFactory(httpClient);
and I can't understand why.
The dependency that I used on my pom.xml is:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
How Can I solve it??
This Code Running Well in my Project
And Call it