RestTemplate发送HTTPS请求

news/2025/2/22 5:38:32/

RestTemplate发送HTTPS请求

基础知识:

Https原理与工作流程及证书校验:https://www.cnblogs.com/zjdxr-up/p/14359904.html

忽略ssl证书的方式配置:

import lombok.extern.slf4j.Slf4j;import org.springframework.http.client.SimpleClientHttpRequestFactory;import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;@Slf4j
public class IgnoreCertificateHttpsClientRequestFactory extends SimpleClientHttpRequestFactory {@Overrideprotected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {try {// 判断类型是http还是httpsif (!(connection instanceof HttpsURLConnection)) {super.prepareConnection(connection, httpMethod);return;}// 强制转换成HttpsURLConnectionHttpsURLConnection httpsConnection = (HttpsURLConnection) connection;// X509TrustManager用于实现SSL证书的安全校验X509TrustManager x509m =new X509TrustManager() {// 返回受信任的X509证书数组。@Overridepublic X509Certificate[] getAcceptedIssuers() {log.info("getAcceptedIssuers");return null;}/*** 该方法检查服务器的证书,若不信任该证书同样抛出异常。通过自己实现该方法,可以使之信任我们指定的任何证书。* 在实现该方法时,也可以简单的不做任何处理,即一个空的函数体,由于不会抛出异常,它就会信任任何证书。*/@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) {log.info("checkServerTrusted");}/*** 该方法检查客户端的证书,若不信任该证书则抛出异常。由于我们不需要对客户端进行认证* 因此我们只需要执行默认的信任管理器的这个方法。Java Secure Socket Extension(JSSE)中,默认的信任管理器类为TrustManager。*/@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {log.info("checkClientTrusted");}};/*** SSLContext的实例表示安全套接字协议实现,它充当安全套接字工厂或SSLEngine的工厂。* 该类使用一组可选的密钥和信任管理器以及安全随机字节源进行初始化。* 获取一个SSLContext实例对象,并使用我们指定的信任管理器初始化*/SSLContext sslContext = SSLContext.getInstance("SSL");/*** 初始化SSL环境* 第二个参数是告诉JSSE使用的可信任证书的来源,设置为null是从javax.net.ssl.trustStore中获得证书* 第三个参数是JSSE生成的随机数,这个参数将影响系统的安全性,设置为null是个好选择,可以保证JSSE的安全性。*/sslContext.init(null, new TrustManager[] {x509m}, new java.security.SecureRandom());// 返回此上下文的 SocketFactory对象。SSLSocketFactory socketFactory = sslContext.getSocketFactory();httpsConnection.setSSLSocketFactory(socketFactory);super.prepareConnection(httpsConnection, httpMethod);} catch (NoSuchAlgorithmException exception) {throw new RuntimeException(exception);} catch (KeyManagementException exception) {throw new RuntimeException(exception);}}
}

使用ssl证书的配置:

import lombok.extern.slf4j.Slf4j;import org.springframework.http.client.SimpleClientHttpRequestFactory;import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;@Slf4j
public class UsingCertificateHttpsClientRequestFactory extends SimpleClientHttpRequestFactory {private String type;private String path;private String password;public UsingCertificateHttpsClientRequestFactory(String type, String path, String password) {super();this.type = type;this.path = path;this.password = password;}@Overrideprotected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {// 判断类型是http还是httpstry {if (!(connection instanceof HttpsURLConnection)) {super.prepareConnection(connection, httpMethod);return;}// 强制转换成HttpsURLConnectionHttpsURLConnection httpsConnection = (HttpsURLConnection) connection;// 加载包含受信任证书的本地密钥库// 建议使用:KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());KeyStore keyStore = KeyStore.getInstance(this.type);try (FileInputStream inputStream = new FileInputStream(this.path); ) {// 使用 keyStore 类将证书库或信任库文件加载进来keyStore.load(inputStream, this.password.toCharArray());log.info("loading jks ...");} catch (CertificateException e) {throw new RuntimeException(e);}// 使用 KeyManagerFactory 和加载了证书库的 Keystore 实例,产生 KeyManager 实例数组// 使用 TrustManagerFactory 和加载了信任库的 Keystore 实例,产生 TrustManager 实例数组TrustManagerFactory trustManagerFactory =TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(keyStore);// 使用 SSLContext 初始化 KeyManager 实例数组和 TrustManager 实例数组,从而设定好通信的环境SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustManagerFactory.getTrustManagers(), new java.security.SecureRandom());// 返回此上下文的 SocketFactory对象。SSLSocketFactory socketFactory = sslContext.getSocketFactory();// 利用 SSLContext 产生的 SSLSocket 或 SSLServerSocket 进行通信httpsConnection.setSSLSocketFactory(socketFactory);super.prepareConnection(httpsConnection, httpMethod);} catch (KeyStoreException exception) {throw new RuntimeException(exception);} catch (NoSuchAlgorithmException exception) {throw new RuntimeException(exception);} catch (KeyManagementException exception) {throw new RuntimeException(exception);}}
}

RestTemplate的配置文件RestTemplateConfiguration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;import java.nio.charset.StandardCharsets;@Configuration
public class RestTemplateConfiguration {@Bean("restTemplate")public RestTemplate restTemplate() {UsingCertificateHttpsClientRequestFactory factory =new UsingCertificateHttpsClientRequestFactory("jks", "D:/truststore.jks", "changeit");// 忽略证书方式: IgnoreCertificateHttpsClientRequestFactory factory = new IgnoreCertificateHttpsClientRequestFactory();factory.setConnectTimeout(5000);factory.setReadTimeout(5000);RestTemplate restTemplate = new RestTemplate(factory);// 解决中文乱码问题restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));return restTemplate;}
}

http://www.ppmy.cn/news/1122361.html

相关文章

Flutter性能监控与优化实践

Flutter是谷歌的移动UI框架,可以快速在iOS和Android上构建高质量的原生用户界面。 Flutter可以与现有的代码一起工作。在全世界,Flutter正在被越来越多的开发者和组织使用,并且Flutter是完全免费、开源的,可以用一套代码同时构建Android和iOS应用,性能可以达到原生应用一样…

【AI视野·今日Robot 机器人论文速览 第三十六期】Tue, 19 Sep 2023

AI视野今日CS.Robotics 机器人学论文速览 Tue, 19 Sep 2023 (showing first 100 of 112 entries) Totally 112 papers 👉上期速览✈更多精彩请移步主页 Interesting: 📚In-Hand Object Rotation, RotateIt 提出了一种基于视觉与触觉的物体旋转朝向的方法…

PRT(Precomputed Radiance Transfer【2002】)原理实现

声明 本文源自对Games202课程,作业2的总结。 参考 手把手教你写GAMES202作业:GAMES202-作业2: Precomputed Radiance Transfer(球谐函数)GAMES 202 作业2Games202课程个人Blog 课程总结:Games202(P6、P7…

Nginx之error_page模块解读

目录 error_page的概念 使用举例 跳转到指定页面 跳转到指定网址 使用location的符合完成错误信息展示 ​更改反馈状态码 error_page配置小提示 实战应用解读 限流应用 寻找错误码对应的文件 error_page的概念 error_page是nginx一个重要的指令,作用是…

【MySQL】 MySQL索引事务

文章目录 🛫索引🎍索引的概念🌳索引的作用🎄索引的使用场景🍀索引的使用📌查看索引📌创建索引🌲删除索引 🌴索引保存的数据结构🎈B树🎈B树&#x…

【draw】draw.io怎么设置默认字体大小

默认情况下draw里面的字体大小是12pt,我们可以将字体改成我们想要的大小,例如18pt。 然后点击样式,设置为默认样式。 下一次当我们使用文字大小时就是18pt了。

PHP8中调换数组中的键值和元素值-PHP8知识详解

在php8中使用array_flip()函数可以调换数组中的键值和元素值。 在PHP8中使用array_flip()函数可以调换数组中的键值和元素值&#xff0c;示范代码如下&#xff1a; <?php$stu array("子涵"> 001,"欣怡"> 002,"梓涵">003,"晨曦…

vue3怎么动态使用style

在 Vue 3 中&#xff0c;你可以使用以下几种方式来动态使用样式&#xff1a; 对象语法&#xff1a;可以通过绑定一个对象来动态设置样式。在模板中使用 :style 指令&#xff0c;并将一个对象作为值传递&#xff0c;对象的键表示样式属性&#xff0c;值表示样式的值。例如&…