• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

HttpClient发送https请求忽略SSL证书

没有忽略时报错

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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959)

忽略https认证,就是自己构建一个x509认证,默认通过,再传到ssl配置工厂中;

  public static CloseableHttpClient trustAll(){
        //配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

//创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();


        return client;
    }

发送请求时调用trustAll()方法返回的client;

发送POST请求

 public static String doPost(Map<String, String> params, String url) throws URISyntaxException {
// 设置请求超时时间 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000) .setConnectionRequestTimeout(3000) .setSocketTimeout(3000) .build(); post.setConfig(requestConfig); System.out.println("url=" + url); String result = ""; try {
// 设置json格式 String strParam = JSONObject.toJSONString(params); StringEntity paramEntity = new StringEntity(strParam); paramEntity.setContentEncoding("utf-8"); paramEntity.setContentType("application/json"); post.setEntity(paramEntity);
//发起请求 , 调用trustAll()方法返回的client HttpResponse httpResponse = trustAll().execute(post); //返回结果 int statusCode = httpResponse.getStatusLine().getStatusCode(); String postReturn = EntityUtils.toString(httpResponse.getEntity()); result = "code=" + statusCode + ",result = " + postReturn; System.out.println(result); } catch (Exception e) { e.printStackTrace(); } return result; }

 

参考:

https://blog.csdn.net/weixin_44671176/article/details/110230719

https://blog.csdn.net/u011221074/article/details/104675035

posted on 2023-02-01 11:50  yxchun  阅读(2756)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3