当前位置:   article > 正文

HttpClient访问https,设置忽略SSL证书验证_httpclient 需要忽略证书校验

httpclient 需要忽略证书校验

访问https时报错:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

解决办法:

1.建立以下工具类,引用信息也标明了,需要注意,引用错了则不好用

  1. import java.security.cert.CertificateException;
  2. import java.security.cert.X509Certificate;
  3. import javax.net.ssl.SSLContext;
  4. import javax.net.ssl.TrustManager;
  5. import javax.net.ssl.X509TrustManager;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  8. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.impl.client.HttpClients;
  11. /**
  12. * @Description 忽略证书验证
  13. * @Author sky
  14. * @Date 2021/10/21 14:00
  15. */
  16. public class CertificateValidationIgnored {
  17. public static HttpClient wrapClient() {
  18. try {
  19. SSLContext ctx = SSLContext.getInstance("TLS");
  20. X509TrustManager tm = new X509TrustManager() {
  21. public X509Certificate[] getAcceptedIssuers() {
  22. return null;
  23. }
  24. public void checkClientTrusted(X509Certificate[] arg0,
  25. String arg1) throws CertificateException {
  26. }
  27. public void checkServerTrusted(X509Certificate[] arg0,
  28. String arg1) throws CertificateException {
  29. }
  30. };
  31. ctx.init(null, new TrustManager[] { tm }, null);
  32. SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
  33. ctx, NoopHostnameVerifier.INSTANCE);
  34. CloseableHttpClient httpclient = HttpClients.custom()
  35. .setSSLSocketFactory(ssf).build();
  36. return httpclient;
  37. } catch (Exception e) {
  38. return HttpClients.createDefault();
  39. }
  40. }
  41. public static void main(String[] args) {
  42. }
  43. }

2.使用工具类,之后就是正常流程了

  1. CertificateValidationIgnored skipHttpsUtil=new CertificateValidationIgnored();
  2. HttpClient httpClient = (CloseableHttpClient)skipHttpsUtil.wrapClient();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/451286
推荐阅读
相关标签
  

闽ICP备14008679号