记录一下Java访问https服务出现的异常情况
2021/4/23 12:28:35
本文主要是介绍记录一下Java访问https服务出现的异常情况,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
异常情况1:
报错拋异常javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
这个情况是由于证书为不是JDK官方信任的证书导致的,解决办法有两种,一种升级代码把校验证书信任忽略,一种是需要访问的服务器本地JDK导入证书。
方案一:
新增类实现X509TrustManager,X509TrustManager这个就是校验信任证书的类,把这个类set到httpsConnection里。
private static class TrustAllManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } }
将AnyHostnameVerifier这个类set进httpsConnection,这个是默认不校验hostname,固定返回true。
httpsConnection.setHostnameVerifier(new AnyHostnameVerifier());
方案二:
把证书下载下来,用keytools导入证书,命令大家网上都可以查到。
异常情况2:
报错抛异常Received fatal alert: handshake_failure
这个异常是由于服务端提供的TLS协议和客户端使用的TLS协议版本不一样。
jdk1.6、jdk1.7默认使用TLS1来连接,jdk8就是默认使用TLS1.2连接。jdk1.7中包含TLS1.2所以可以通过设置启动参数来让jdk强制使用TLS1.2来连接。
参数如下:
-Dhttps.protocols=TLSv1.2
最好的解决办法是服务端的前端网关进行全协议适配,如nginx、F5等配置全协议支持。
这篇关于记录一下Java访问https服务出现的异常情况的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求