经常遇到自签证书,java不认识的情况。一般都是将证书copy到jdk路径 或通过代码加载自签证书,已使通过https访问资源,能够通过SSL握手验证。
以上两种方法,都比较麻烦。 先说思路,通过忽略ssl 证书,废话不多说,直接上代码。依赖org.apache.httpcomponents.httpclient
1. 直接使用http client ,通过配置 SSLConnectionSocketFactory 的 TrustStrategy 验证策略
TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> 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();
2. 通过配置spring restTemplate
RestTemplate restTemplate=new RestTemplate();
TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> 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 = new RestTemplate(requestFactory);
只在确认访问服务可信时,才使用,不然会存在安全问题。