转载请注明出处:

1.http协议请求

  使用RestTemplate进行http协议的请求时,不需要考虑证书验证相关问题,以下为使用RestTemplate直接使用的代码示例:

import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; public class HttpRestClient { public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/endpoint"; // 注意这里是HTTP协议
HttpHeaders headers = new HttpHeaders();
// 可以在这里添加请求头,如果需要的话
HttpEntity<?> requestEntity = new HttpEntity<>(headers); try {
ResponseEntity<String> responseEntity = restTemplate.exchange(
url,
HttpMethod.GET, // 或者使用其他HTTP方法,如POST、PUT等
requestEntity,
String.class // 指定响应体的类型
); // 处理响应
if (responseEntity.getStatusCode().is2xxSuccessful()) {
String responseBody = responseEntity.getBody();
System.out.println("Response: " + responseBody);
} else {
System.out.println("Request failed with status: " + responseEntity.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

2.Https请求信任所有证书:

  在Java中,使用RestTemplate进行HTTP请求时,默认情况下它会验证HTTPS证书的有效性。如果想要忽略HTTPS证书验证(这通常不推荐,因为它会降低安全性),需要自定义一个HttpClient并设置它忽略SSL证书验证。

  以下是一个示例,展示了如何为RestTemplate创建一个自定义的HttpClient,该HttpClient将忽略HTTPS证书验证:

  1. 创建一个忽略SSL证书验证的HttpClient

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.HttpClients;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; public CloseableHttpClient createTrustingHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, (chain, authType) -> true) // 信任所有证书
.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
}

  2.使用自定义的HttpClient创建RestTemplate

import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; public RestTemplate createRestTemplateWithTrustingHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(createTrustingHttpClient()); return new RestTemplate(factory);
}

  3.使用RestTemplate进行请求

public void makeRequest() throws NoSuchAlgorithmException, KeyManagementException {
RestTemplate restTemplate = createRestTemplateWithTrustingHttpClient(); String url = "https://example.com/api/endpoint";
RequestEntity<?> requestEntity = RequestEntity.get(URI.create(url)).build();
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class); // 处理响应...
}  

注意

  • 忽略SSL证书验证会降低你的应用的安全性,因为它容易受到中间人攻击。在生产环境中,你应该始终验证SSL证书。

  • 如果确实需要忽略证书验证,确保完全了解相关的安全风险,并在完成后尽快恢复正常的证书验证。

3.自定义加载证书

  在Java中使用RestTemplate进行HTTPS请求时,如果需要加载特定的HTTPS证书,通常需要使用一个自定义的HttpClient,并配置SSL上下文以加载你的证书。以下是一个使用Apache HttpClient和Spring RestTemplate加载特定HTTPS证书的示例:

  1. 创建自定义的HttpClient

  需要创建一个自定义的HttpClient,并配置SSL上下文以加载你的证书。

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException; public class CustomRestTemplate { public static RestTemplate createRestTemplateWithCustomSSL() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
// 加载你的证书和私钥
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream certStream = new FileInputStream("path/to/your/cert.p12")) {
keyStore.load(certStream, "password".toCharArray()); // 替换为你的证书密码
} KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "password".toCharArray()); // 替换为你的证书密码 TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyManagerFactory, "password".toCharArray()) // 替换为你的证书密码
.loadTrustMaterial(trustManagerFactory)
.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.NO_HOSTNAME_VERIFIER); CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}

  在上面的代码中,你需要替换path/to/your/cert.p12为你的证书文件路径,以及替换password为你的证书密码。

  2.使用自定义的RestTemplate

  现在你可以使用上面创建的RestTemplate实例进行HTTPS请求了。

public class MyService {  

    private final RestTemplate restTemplate;  

    public MyService() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
this.restTemplate = CustomRestTemplate.createRestTemplateWithCustomSSL();
} public String makeHttpsRequest(String url) {
return restTemplate.getForObject(url, String.class);
}
}

RestTemplate进行https请求时适配信任证书的更多相关文章

  1. nginx https ssl 设置受信任证书[转然哥]

    nginx https ssl 设置受信任证书[原创] 1. 安装nginx 支持ssl模块 http://nginx.org/en/docs/configure.html yum -y instal ...

  2. java在访问https资源时,忽略证书信任问题 (转)

    java程序在访问https资源时,出现报错sun.security.validator.ValidatorException: PKIX path building failed: sun.secu ...

  3. nginx https ssl 设置受信任证书[原创]

    1. 安装nginx 支持ssl模块 http://nginx.org/en/docs/configure.html yum -y install openssh openssh-devel (htt ...

  4. 用curl获取https请求时出现错误的处理

    今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...

  5. python2/3 发送https请求时,告警关闭方法

    问题: 使用Python3 requests发送HTTPS请求,已经关闭认证(verify=False)情况下,控制台会输出以下错误: InsecureRequestWarning: Unverifi ...

  6. C#模拟Https请求时出现 基础连接已经关闭 未能为 SSLTLS 安全通道建立信任关系

    //解决方法: //引入命名空间: using System.Security.Cryptography.X509Certificates; using System.Net.Security; // ...

  7. https请求时出错:Could not establish trust relationship for the SSL/TLS secure channel

    当我在用NET命名空间下获取URL的时候,提示如下错误: The underlying connection was closed: Could not establish trust relatio ...

  8. AFNetWorking https请求 SSL认证 自制证书

    1.服务器会给一个证书,一般为.pem格式证书 2.将.pem格式的证书转换成.cer格式的证书 打开电脑自带终端 ,进入到桌面  cd Desktop 回车回到桌面Desktop Admin$ 输入 ...

  9. WinInet:HTTPS 请求出现无效的证书颁发机构的处理

    首先,微软提供的WinInet库封装了对网页访问的方法. 最近工作需要从https服务器获取数据,都知道https和http网页的访问方式不同,多了一道证书认证程序,这样就使得https在请求起来比h ...

  10. IE打开https网站时,取消证书问题提示

    上面介绍了,调用IE来打开对应的网页问题,但是在实际测试中,有些网站是采用https协议的,这时候IE浏览器会弹出如下窗口,一般手动选择后,才可进入登录界面,那么该如何解决呢? 1.点击[继续浏览此网 ...

随机推荐

  1. Kconnect使用sftp windows自定义协议

    终于有时间写点东西了,上次写东西已经是三个月之前了.自从出现了觉得一个月写一篇文章也没关系的想法之后就已经完全忘记有这回事儿了.一直觉得没有足够的时间,但是又想写出质量比较好的文章,所以就一直没有动笔 ...

  2. 多个 .NET Core SDK 版本之间进行切换 global.json

    由于同一台电脑可以安装多个版本的.NET Core SDK. 当安装了许多不同版本的.NET Core SDK 之后,要如何才能使用旧版dotnet 命令,执行dotnet new 或dotnet b ...

  3. Zabbix“专家坐诊”第187期问答汇总

    问题一 Q:zabbix server 5.0有办法不通过脚本监控SSL证书到期时间么? A:目前还是流行通过脚本方式去获取. Q:如果是通配符证书应该怎么监控? A:通过解析域名获取对应的过期时间的 ...

  4. C#串口开发之SerialPort类封装

    目录 SerialPort类 参数封装 控件操作封装 SerialPortClient类实现 SerialPortClient类使用 测试Demo 参考文章 SerialPort类 微软在.NET中对 ...

  5. 单点登录之CAS简单介绍

    cas官网http://www.ja-sig.org/products/cas/. ok,现在开始本文的重点内容讲解,先来了解一下cas 实现single sign out的原理,如图所示:      ...

  6. [极客大挑战 2019]web部分题解(已完结!)

    SQL部分: [极客大挑战 2019]BabySQL 打开环境后有登录界面◕‿◕ 一眼注入,后先试试万能密码: username:admin' or '1'='1 password:1 GG,出大问题 ...

  7. HttpClient 3.1 发送 https 请求跳过验证

    环境: 依赖: <dependency> <groupId>commons-httpclient</groupId> <artifactId>commo ...

  8. 二次元 & 动漫壁纸网站(内容记录)

    前言 天天和电脑.手机以及平板等电子设备打交道,一个好看的桌面壁纸图片当然是必不可少的,也曾经分享过<值得珍藏的高清壁纸网站推荐>,各种类型和分辨率的壁纸都有. 今天再分享些「高清二次元& ...

  9. Java22重磅发布!!!!卷不动了,真的卷不动了。。。。

    就在3月19日,Java22重磅发布.Java22新增了12项增强功能,其中包括七个预览特性和一个孵化器特性,这些功能都显著到足以引起JDK增强提案(JEPs)的关注.它们涵盖了Java语言.其API ...

  10. 开发进阶系列:Java并发之从基础到框架

    一  线程基础 1.synchronized取得的锁都是对象锁,哪个线程执行synchronized修饰的方法,哪个线程就获得这个方法所属对象的锁.不同对象不同锁,互不影响. 另一种情况是static ...