当前位置: 首页 > news >正文

RestTemplate发送HTTPS请求

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.lryc.cn/news/177494.html

相关文章:

  • 图像练习-矩形4点OpenCV(01)
  • 不同层设置不同学习率
  • 剑指offer32Ⅰ:从上到下打印二叉树
  • 【VUE复习·8】v-if;v-show高级
  • 线程同步需要注意什么?
  • 力扣算法题:35、搜索插入位置.java版
  • 七、热力图展示
  • 基于微信小程序的新闻发布平台小程序设计与实现(源码+lw+部署文档+讲解等)
  • 【论文阅读】Directional Connectivity-based Segmentation of Medical Images
  • 借“牛油果”爆款出圈,甜啦啦的底牌只是“价格”?
  • 【C语言】快速排序
  • Java列表查询Long(id)到前端转换出错
  • react import爆红
  • ThreeJS-3D教学三:平移缩放+物体沿轨迹运动
  • 玩玩“小藤”开发者套件 Atlas 200I DK A2 之VSCode远程连接
  • 安装python中tensorflow和keras==2.2.0的路程
  • Linux命令历史记录管理:使用history命令提高工作效率
  • Armv9 Cortex-A720的L1 memory system 和 L1 Cache
  • 使用超声波清洗机洗眼镜有哪些注意事项、高颜值超声波清洗机推荐
  • 23种设计模式汇总详解
  • stream流的filter和map过滤
  • Linux 环境下使用 Docker 部署 Seata 1.7.1 (图文教程)
  • Aruba CX交换机 VSF配置
  • 使用ElementUI结合Vue完善主页的导航菜单和书籍管理以及后台数据分页查询
  • 子序列问题集合
  • idea中提示:error has occurred, please check your installation and try again
  • MySQL - 关于约束类型和作用的介绍
  • 【2023集创赛】芯原杯一等奖作品:基于芯原DSP核的智能语音SoC设计
  • 代理IP与Socks5代理在跨界电商、爬虫、游戏和网络安全中的应用
  • DDS信号发生器Verilog波形发生器FPGA