向https地址发送请求失败报错

错误1:

10:13:47.520 [main] DEBUG org.apache.http.conn.ssl.SSLConnectionSocketFactory - Starting handshake
10:13:47.523 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: Shutdown connection
10:13:47.523 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection discarded
10:13:47.523 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {s}->https://223.108.104.37:8180][total available: 0; route allocated: 0 of 2; total allocated: 0 of 20]
10:13:47.524 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down
10:13:47.524 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager shut down
Exception in thread "main" javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:106)at sun.security.ssl.TransportContext.kickstart(TransportContext.java:245)at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410)at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:389)at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436)at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
  • SSLHandshakeException 异常:我这边是使用的协议TLSv1版本太低,换一个就行
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[]{"TLSv1.2"},  // 使用 TLSv1.2 协议null,NoopHostnameVerifier.INSTANCE);

错误2:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun.security.ssl.Alert.createSSLException(Alert.java:131)at sun.security.ssl.TransportContext.fatal(TransportContext.java:377)at sun.security.ssl.TransportContext.fatal(TransportContext.java:320)at sun.security.ssl.TransportContext.fatal(TransportContext.java:315)at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:652)at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:471)at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:367)at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:376)at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:479)at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:457)at sun.security.ssl.TransportContext.dispatch(TransportContext.java:200)at sun.security.ssl.SSLTransport.decode(SSLTransport.java:155)at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1320)at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1233)at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:417)at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:389)at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436)at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)at com.waterapidemo.util.HttpPostUtil.sslRequest(HttpPostUtil.java:108)at com.waterapidemo.util.HttpPostUtil.main(HttpPostUtil.java:74)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)at sun.security.validator.Validator.validate(Validator.java:271)at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:312)at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:221)at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:128)at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:636)... 25 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:148)
  • ​JVM默认信任证书不包含该目标网站的SSL证书,导致无法建立有效的信任链接。

keytool -importcert -alias xxx.xxx.xxx.xxx -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file xxxxx.cert 

 解决办法:

1.获取服务器的证书

package com.waterapidemo.util;import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;public class FetchServerCert {private static final String SERVER_HOST = "xxxxxxxxx";private static final int SERVER_PORT = xxxx;private static final String CERT_FILE = "X:\\xxx\\server-cert.cer";public static void main(String[] args) {try {// Step 1: Set up a TrustManager that accepts all certificatesTrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}}};SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());SSLSocketFactory factory = sslContext.getSocketFactory();// Step 2: Connect to the server and retrieve the server certificatetry (SSLSocket socket = (SSLSocket) factory.createSocket(SERVER_HOST, SERVER_PORT)) {socket.startHandshake();Certificate[] serverCerts = socket.getSession().getPeerCertificates();// Step 3: Save the first server certificate to a filetry (FileOutputStream fos = new FileOutputStream(CERT_FILE)) {fos.write(serverCerts[0].getEncoded());}System.out.println("Server certificate saved to " + CERT_FILE);}} catch (Exception e) {e.printStackTrace();}}
}
  • 定义一个自定义的 TrustManager,它将接受所有证书

2.将证书导入JVM信任库

package com.waterapidemo.util;import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;public class ImportServerCert {private static final String CERT_FILE = "X:\\xxx\\server-cert.cer";private static final String TRUSTSTORE_PATH = "X:\\xxx\\truststore.jks";private static final String TRUSTSTORE_PASSWORD = "changeit";public static void main(String[] args) {try {// Load the server certificate from the fileCertificate serverCert = loadCertificate(CERT_FILE);// Create a truststore and add the server certificate to itKeyStore trustStore = createTrustStore(serverCert, TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD);// Save the truststore to a filetry (FileOutputStream fos = new FileOutputStream(TRUSTSTORE_PATH)) {trustStore.store(fos, TRUSTSTORE_PASSWORD.toCharArray());System.out.println("Truststore created and saved to " + TRUSTSTORE_PATH);}} catch (Exception e) {e.printStackTrace();}}private static Certificate loadCertificate(String certFilePath) throws Exception {CertificateFactory cf = CertificateFactory.getInstance("X.509");try (FileInputStream fis = new FileInputStream(certFilePath)) {return cf.generateCertificate(fis);}}private static KeyStore createTrustStore(Certificate cert, String trustStorePath, String trustStorePassword) throws Exception {KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());trustStore.load(null, null); // Initialize the empty truststoreString alias = "server-cert";trustStore.setCertificateEntry(alias, cert);return trustStore;}
}

3.请求的时候携带好证书就可以了

    public static String sslRequest(String url, String params, String token) throws Exception {String results;// Load client certificateKeyStore keyStore = KeyStore.getInstance("xxxx");try (FileInputStream keyStoreStream = new FileInputStream(PATH)) {keyStore.load(keyStoreStream, PASSWORD.toCharArray());}// Load truststore containing server certificateKeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());try (FileInputStream trustStoreStream = new FileInputStream(TRUSTSTORE_PATH)) {trustStore.load(trustStoreStream, TRUSTSTORE_PASSWORD.toCharArray());}// Set up SSL context with client certificate and truststoreSSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, PASSWORD.toCharArray()).loadTrustMaterial(trustStore, null).build();// Create SSL connection factorySSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);// Create HTTP client with custom SSL contexttry (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {// Create HTTP POST requestHttpPost httpPost = new HttpPost(url);httpPost.setHeader("FROM", token);httpPost.setEntity(new StringEntity(params, "UTF-8"));// Execute requesttry (CloseableHttpResponse response = httpClient.execute(httpPost)) {HttpEntity entity = response.getEntity();results = EntityUtils.toString(entity, "UTF-8");EntityUtils.consume(entity);}}return results;}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/28271.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vue 应用测试(一) --- 介绍

vue 应用测试&#xff08;一&#xff09; ---介绍 前端测试简介组件测试Jest 测试框架简介其他测试框架 第一个测试避免误报如何组织测试代码 组件挂载Vue2 组件挂载的方式Vue3 的挂载方式vue-test-utils挂载选项 如何调试测试用例参考小结 前端测试简介 软件测试&#xff1a;…

[AIGC] Python的Range函数

Python的range()函数是一个内置函数&#xff0c;常常用于编程中生成数列。这个函数可以生成一个整数序列&#xff0c;这个序列通常用在循环中。 文章目录 基本用法详细用法注意事项 基本用法 range()函数的基本形式为 range(stop) —— 这将生成一个从0开始&#xff0c;到stop…

Docker_1.0

1.初识Docker 1.1.什么是Docker 微服务虽然具备各种各样的优势&#xff0c;但服务的拆分通用给部署带来了很大的麻烦。 - 分布式系统中&#xff0c;依赖的组件非常多&#xff0c;不同组件之间部署时往往会产生一些冲突。 - 在数百上千台服务中重复部署&#xff0c;环境不一…

(60)MOS管专题--->(15)MOS场效应管

(15)MOS场效应管 1 目录 (a)IC简介 (b)数字IC设计流程 (c)Verilog简介 (d)MOS场效应管 (e)结束 1 IC简介 (a)在IC设计中,设计师使用电路设计工具(如EDA软件)来设计和模拟各种电路,例如逻辑电路、模拟电路、数字信号处理电路等。然后,根据设计电路的…

Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported

Content type application/x-www-form-urlencoded;charsetUTF-8 not supported 问题背景新增页面代码改造 问题背景 这里有一个需求&#xff0c;前端页面需要往后端传参&#xff0c;参数包括主表数据字段以及子表数据字段&#xff0c;由于主表与子表为一对多关系&#xff0c;在…

基于单片机的多功能智能小车设计

第一章 绪论 1.1 课题背景和意义 随着计算机、微电子、信息技术的快速发展,智能化技术的发展速度越来越快,智能化与人们生活的联系也越来越紧密,智能化是未来社会发展的必然趋势。智能小车实际上就是一个可以自由移动的智能机器人,比较适合在人们无法工作的地方工作,也可…

python基础面试器(其一)

一&#xff0c; 你为什么主要学习的是python语言&#xff1f; 我觉得python 是一门优秀的综合语言&#xff0c;python的宗旨就是简明&#xff0c;优雅&#xff0c;强大&#xff0c;在数据采集&#xff0c;人工智能&#xff0c;云计算&#xff0c;金融分析&#xff0c;大数据开…

C++ 12 之 指针引用

c12指针引用.cpp #include <iostream>using namespace std;struct students12 {int age; };int main() {students12 stu;students12* p &stu; // 结构体指针students12* &pp p; // 结构体指针起别名pp->age 20;// (*pp).age 22;cout << "…

【CTF Web】CTFShow 探针泄露 Writeup(PHP+探针泄露+信息收集)

探针泄露 10 对于测试用的探针&#xff0c;使用完毕后要及时删除&#xff0c;可能会造成信息泄露 解法 查看网页源代码。 view-source:https://11170dfe-84c7-4fde-b1ca-5d1ec3dd7570.challenge.ctf.show/没有找到有用的信息。 用 dirsearch 扫描。 dirsearch -u https://1…

打造私密的通信工具,极空间搭建免费开源的电子邮件管理程序『Cypht』

打造私密的通信工具&#xff0c;极空间搭建免费开源的电子邮件管理程序『Cypht』 哈喽小伙伴门好&#xff0c;我是Stark-C~ 说起电子邮件大家都不陌生&#xff0c;哪怕是在当前微信或者QQ已经非常普遍的今天&#xff0c;电子邮件在我们很多人的工作中都充当了重要的通信工具。…

【TB作品】基于STM32单片机的实验室器材管理登记二维码系统

这个单片机代码实现了一个实验室管理系统&#xff0c;该系统的主要功能包括记录和管理ID信息、日期和时间、以及显示这些信息到OLED屏幕上。以下是对代码主要功能的分析&#xff1a; 全局变量定义 定义了多个全局变量来存储系统状态、页面、密码、ID列表等信息。time 结构体用…

专题六——模拟

目录 一替换所有的问号 二提莫攻击 三N字形变换 四外观数列 五数青蛙 一替换所有的问号 oj链接&#xff1a;替换所有的问号 思路&#xff1a;简单模拟&#xff1b;注意i0和in是处理越界问题就行&#xff01;&#xff01; class Solution { public:string modifyString…

GenericObjectPool对象池化的介绍与用法

前言 GenericObjectPool 是 Apache Commons Pool 库的一部分&#xff0c;它提供了一个通用的对象池实现&#xff0c;允许用户在需要时从池中借用和返回对象&#xff0c;而不是每次需要一个新实例时都创建一个。这种方法可以显著提高性能&#xff0c;特别是对于创建开销大或需要…

【日常刷题】为什么二分法不建议使用 (right + left) / 2?

为什么二分法不建议使用 (right left) / 2&#xff1f; 用left(right-left)/2,而不用(leftright)/2是担心后者(rightleft)的值过大超过了整形的取值范围造成溢出&#xff0c;使结果不准确 就拿奇偶个数来看就知道什么原因了。 valueOf() 当有一个参数时AAA.valueOf(BBB)的…

跨域资源共享(CORS)问题与解决方案

跨域资源共享&#xff08;CORS&#xff0c;Cross-Origin Resource Sharing&#xff09;是现代web开发中常见且重要的一个概念。它涉及到浏览器的同源策略&#xff08;Same-Origin Policy&#xff09;&#xff0c;该策略用于防止恶意网站从不同来源窃取数据。然而&#xff0c;在…

Web前端与软件测试:探索技术与质量的双重世界

Web前端与软件测试&#xff1a;探索技术与质量的双重世界 在数字化时代的浪潮中&#xff0c;Web前端技术和软件测试扮演着举足轻重的角色。它们犹如一对默契的舞者&#xff0c;在技术的舞台上共同演绎着精彩绝伦的舞蹈。本文将从四个方面、五个方面、六个方面和七个方面&#…

Java实现Mysql批量插入与更新

第一、批量插入语句 Insert({"<script>","INSERT INTO TABLE_NAME (" "ID," "IS_DELETE," "GMT_CREATE," "GMT_MODIFIED" ")VALUES","<foreach collection list item item separator …

docker容器基本原理简介

一、docker容器实例运行的在linux上是一个进程 1&#xff09;、我们通过docker run 通过镜像运行启动的在linux上其实是一个进程&#xff0c;例如我们通过命令运行一个redis&#xff1a; docker run -d --name myredis redis2&#xff09;、可以看到首先我们本地还没有redis镜…

【LeetCode最详尽解答】11-盛最多水的容器 Container-With-Most-Water

欢迎收藏Star我的Machine Learning Blog:https://github.com/purepisces/Wenqing-Machine_Learning_Blog。如果收藏star, 有问题可以随时与我交流, 谢谢大家&#xff01; 链接&#xff1a; 11-盛最多水的容器 直觉 这个问题可以通过可视化图表来理解和解决。 通过图形化这个…

「动态规划」如何求乘积最大子数组?

152. 乘积最大子数组https://leetcode.cn/problems/maximum-product-subarray/description/ 给你一个整数数组nums&#xff0c;请你找出数组中乘积最大的非空连续子数组&#xff08;该子数组中至少包含一个数字&#xff09;&#xff0c;并返回该子数组所对应的乘积。测试用例的…