关于调用第三方https接口的错误

问题背景:在一个卫健局的app上有一个报告单查询,要求新增一个返显用户姓名以及手机号(不需要用户手动输入了,旨在方便用户)。根据app传过来的token,调用他们的接口,获取用户信息并返显(一个简单到不能再简单的功能)。做完了之后并上线了,直到昨天,发现线上功能报了500.
报错信息如下:

[23:14:09:981] [ERROR] - cn.ucmed.common.core.exception.RRExceptionHandler.handleException(RRExceptionHandler.java:32) - I/O error on GET request for "https://#####": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is 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
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://###": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is 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
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743) ~[spring-web-5.1.4.RELEASE.jar!/:5.1.4.RELEASE]

明显提示说是证书的问题,翻了翻csdn以及Stack Overflow发现是java在调用https接口的过程中,需要对该网站信任,也就是需要获取网站的安全证书(然而本地跑项目毫无问题。。。)。
这样一般有两种解决方式:一个是导入证书,另一个是让项目信任所有的ssl
第一种导入证书的方式十分安全,但是接口方频繁更新证书,自己这边也必须更新。
第二种方式相对而言比较懒人化,但也是更加符合实际情况的解决方式。
这里只介绍第二种方式,代码如下:

    private static CloseableHttpClient httpClient;

    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

只需要在调用的service加上以上代码即可。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值