目标URL开启了证书验证。怎么改?方法是在发送的请求那里设置证书忽略(思路是这样的,我现在的方法是当前使用的,未来也许不适用,但是思路没错)
在这里我发送http请求的工具是RestTemplate,我们需要自己设置一下RestTemplate证书忽略。
@Configuration
public class RestTemplateConfig
{private Integer connectTimeout = 300000;private Integer readTimeout = 300000;@Bean("sslRestTemplate")public RestTemplate RestTemplate(){SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();httpRequestFactory.setConnectTimeout(connectTimeout);httpRequestFactory.setReadTimeout(readTimeout);return new RestTemplate(httpRequestFactory);}/*** 用于https请求,忽略认证** @return unSSLRestTemplate*/@Bean("unSSLRestTemplate")@Primarypublic RestTemplate restTemplateHttps(){RestTemplate restTemplate = null;try{SSL factory = new SSL();factory.setConnectTimeout(connectTimeout);factory.setReadTimeout(readTimeout);restTemplate = new RestTemplate(factory);//解决乱码List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();httpMessageConverters.stream().forEach(httpMessageConverter ->{if (httpMessageConverter instanceof StringHttpMessageConverter){StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;messageConverter.setDefaultCharset(Charset.forName("UTF-8"));}});}catch (Exception e){e.printStackTrace();}return restTemplate;}
}
这里的SSL文件如下:
public class SSL extends SimpleClientHttpRequestFactory {@Overrideprotected void prepareConnection(HttpURLConnection connection, String httpMethod)throws IOException {if (connection instanceof HttpsURLConnection) {prepareHttpsConnection((HttpsURLConnection) connection);}super.prepareConnection(connection, httpMethod);}private void prepareHttpsConnection(HttpsURLConnection connection) {connection.setHostnameVerifier(new SkipHostnameVerifier());try {connection.setSSLSocketFactory(createSslSocketFactory());}catch (Exception ex) {}}private SSLSocketFactory createSslSocketFactory() throws Exception {SSLContext context = SSLContext.getInstance("TLS");context.init(null, new TrustManager[] { new SkipX509TrustManager() },new SecureRandom());return context.getSocketFactory();}private class SkipHostnameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String s, SSLSession sslSession) {return true;}}private static class SkipX509TrustManager implements X509TrustManager {@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) {}}}
这样配置完的RestTemplate就可以发送忽略证书的请求。
原文取自:Springboot 使用RestTemplate 跳过SSL证书验证完成请求_springboot 绕过ssl-CSDN博客