发送https请求并跳过ssl证书验证

12 篇文章 0 订阅
8 篇文章 0 订阅

 平台服务调用https接口报错:

org.springframework.web.client.ResourceAccessException: I/0 error on PoST request for ?"https://XXXXX": java.security.centp.CertificateException: No subject alternative names present; nested exception is javax.net.ssl..SSLHandshakeException: java.security.cert.CertificateException: No subject alternative namesspresent

第一种方法:配置相关SSL证书到服务器

第二种方法:如果没有相关服务器权限,又想快速验证接口调用,可以在请求时添加跳过SSL证书,可以 快捷实现,当然生产环境还是建议配置证书方式,降低风险

/**
     * 发送https请求并跳过ssl证书验证
     * 条件:请求体格式为json
     *
     * @param url
     * @param body
     * @return
     */
    public static String sendAskSkipSSLCertificate(String url, Map<String, Object> body, Map<String, String> header) throws Exception {

        CloseableHttpResponse response = null;
        // 处理请求路径
        url = UriComponentsBuilder.fromHttpUrl(url) .toUriString();
        //创建httpclient对象
        CloseableHttpClient client = null;
        String respBody;
        client = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
                        .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE)).build();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 请求头设置
        httpPost.setHeader("Content-Type", "application/json");
        if (header != null) {
            for (String s : header.keySet()) {
                httpPost.setHeader(s, header.get(s));
            }
        }
        if (body != null) {
            httpPost.setEntity(new StringEntity(JSON.toJSONString(body), "utf-8"));
        }
        response = client.execute(httpPost);
        org.apache.http.HttpEntity entity = response.getEntity();
        if (entity != null) {
            respBody = EntityUtils.toString(entity);
            return respBody;
        }
        return null;
 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值