Java – certificates need to be ignored when using resttemplate
•
Java
I am sending a request to the following address The certificate is invalid. I want to ignore it I wrote the following code based on my research in 1 and 2, but I can't complete it I'm using java 1.7,
https://api.stubhubsand@R_962_2419@.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.stubhubsand@R_962_2419@.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"); }
Solution
You may have noticed that spring's resttemplate delegates all HTTP (s) - related content to the underlying implementation of clienthttprequestfactory Since you are using an httpclient based implementation, here are some useful links on how to implement this function for an internal httpclient:
> Ignoring SSL certificate in Apache HttpClient 4.3 > How to ignore SSL certificate errors in Apache HttpClient 4.0
Obviously, since version 4.4, this can be done:
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码