gpt4 book ai didi

java - 使用 Spring RestTemplate 时忽略 SSL 证书验证

转载 作者:行者123 更新时间:2023-12-05 01:16:12 67 4
gpt4 key购买 nike

我正在使用 Spring RestTemplate 发出 HTTPS 请求,我想忽略 SSL 证书

这是我创建 restTemplate 请求的代码:

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String 
authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new
SSLConnectionSocketFactory(sslContext);
loseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
...
response = restTemplate.exchange("https://192.168.1.2:/foo/bar",
HttpMethod.POST, entity,String.class);

当我使用服务器主机名时,这个请求有效,但是当我使用服务器 IP 地址时出现以下异常:

Exception in thread "main" 
org.springframework.web.client.ResourceAccessException: I/O error on POST
request for "https://192.168.1.2/foo/bar": Certificate for
<192.168.1.2> doesn't match any of the subject alternative names: [];
nested exception is javax.net.ssl.SSLPeerUnverifiedException: Certificate
for <192.168.1.2> doesn't match any of the subject alternative names: []

Caused by: javax.net.ssl.SSLPeerUnverifiedException: Certificate for
<192.168.1.2> doesn't match any of the subject alternative names: []

最佳答案

@Bean
public RestTemplate restTemplate() throws GeneralSecurityException {

TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();

BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

return restTemplate;
}

关于java - 使用 Spring RestTemplate 时忽略 SSL 证书验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038334/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com