RestTemplate请求https ip 忽略证书不安全问题

restTemplate请求https的ip地址时,会报错:

No subject alternative names matching IP address … found

同样的,在浏览器直接访问浏览器也会提示该地址不安全/证书无效。在高级选项里面可以忽略提示并继续前往。

后端直接请求时,也可以对restTemplate配置ssl安全策略来实现强制信任ssl证书,完整配置如下:


package xxx.common.config;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
impor
如果你想在使用 RestTemplate 发送 POST 请求忽略证书,可以通过创建一个自定义的 RestTemplate 来实现。下面是一个示例代码: ```java import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class CustomRestTemplate extends RestTemplate { public CustomRestTemplate() { super(); setRequestFactory(new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); ((HttpsURLConnection) connection).setSSLSocketFactory(createSslSocketFactory()); } super.prepareConnection(connection, httpMethod); } }); } private static SSLSocketFactory createSslSocketFactory() { SSLSocketFactory sslSocketFactory = null; try { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return sslSocketFactory; } } ``` 在上面的代码中,我们创建了一个自定义的 RestTemplate,其中重写了 prepareConnection 方法,在发送 HTTPS 请求忽略证书。 使用这个自定义的 RestTemplate,只需要在代码中实例化它并使用即可: ```java CustomRestTemplate restTemplate = new CustomRestTemplate(); String result = restTemplate.postForObject(url, request, String.class); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值