Skip to content

Instantly share code, notes, and snippets.

@muhdkhokhar
Created October 20, 2024 11:57
Show Gist options
  • Save muhdkhokhar/04b47045d75f01ec422aa98d66a094cd to your computer and use it in GitHub Desktop.
Save muhdkhokhar/04b47045d75f01ec422aa98d66a094cd to your computer and use it in GitHub Desktop.
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class CustomOAuth2RestTemplate {
public OAuth2RestTemplate createOAuth2RestTemplate() throws Exception {
// Create an SSL context that trusts all certificates
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial((chain, authType) -> true)
.build();
// Create an HttpClient with the NoopHostnameVerifier to bypass hostname checks
HttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
// Use the HttpClient in the request factory
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(5000);
requestFactory.setReadTimeout(10000);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate();
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment