I am trying to send a request to following address. The certificate is not valid and I would like to ignore it. I wrote following code based on my research on 1, 2 but I am not able to complete it. I am using Java 1.7,
https://api.stubhubsandbox.com/search/catalog/events/v3 Code
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers(){ return null; } public void checkClientTrusted( X509Certificate[] certs, String authType ){} public void checkServerTrusted( X509Certificate[] certs, String authType ){} public void checkClientTrusted( java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } public void checkServerTrusted( java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } } }; public static void main(String[] args) { TrustStrategy acceptingTrustStrategy = SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(csf) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); String url = "https://api.stubhubsandbox.com/search/catalog/events/v3"; RestTemplate rest = new RestTemplate(); Map<String, String> mvm = new HashMap<String, String>(); mvm.put("Authorization", "Bearer TOKEEEEEEEN"); Object object = rest.postForObject(url, null, Object.class, mvm); System.err.println("done"); }
To skip or avoid the SSL check, we need to modify the default RestTemplate available with the normal Spring package. In this configuration class, we basically declare a new Bean that creates a HTTPClient with the certificate check as disabled.
As you may have noticed, Spring's RestTemplate delegates all the HTTP(S) related stuff to the underlying implementation of ClientHttpRequestFactory. Since you're using the HttpClient-based implementation, here are a couple of useful SO links on how to achieve this for the internal HttpClient:
Apparently, since version 4.4, this can be done as:
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With