当前位置:   article > 正文

http忽略ssl认证

http忽略ssl认证

我们在发请求时,会遇到需要ssl证书验证的报错,针对该错误以及所使用的不同的创建连接的方式,进行ssl证书忽略

忽略SSL证书的流程

简介:需要告诉client使用一个不同的TrustManager。TrustManager是一个检查给定的证书是否有效的类。SSL使用的模式是X.509,对于该模式Java有一个特定的TrustManager,称为X509TrustManager。首先我们需要创建这样的TrustManager。将TrustManager设置到我们的HttpClient。TrustManager只是被SSL的Socket所使用。Socket通过SocketFactory创建。对于SSL Socket,有一个SSLSocketFactory。当创建新的SSLSocketFactory时,你需要传入SSLContext到它的构造方法中。在SSLContext中,我们将包含我们新创建的TrustManager。

  1. 创建的TrustManager
  2. 创建SSLContext:TLS是SSL的继承者,但是它们使用相同的SSLContext。
  3. 创建SSLSocketFactory
  4. 将SSLSocketFactory注册到我们的HttpClient上。这是在SchemeRegistry中完成的。
  5. 创建ClientConnectionManager,创建SchemeRegistry。
  6. 生成HttpClient

http忽略ssl认证

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

1. httpClient忽略ssl证书连接

client发起请求时,使用已经构建过认证client发起请求

  1. package com.neo.address.parse;
  2. /**
  3. * @author caoying
  4. * @since 2024/4/14
  5. */
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  9. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  10. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  11. import org.apache.http.conn.ssl.TrustStrategy;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.ssl.SSLContexts;
  15. import org.apache.http.util.EntityUtils;
  16. import org.jsoup.Jsoup;
  17. import org.jsoup.nodes.Document;
  18. import org.jsoup.nodes.Element;
  19. import org.jsoup.select.Elements;
  20. import javax.net.ssl.SSLContext;
  21. import java.io.IOException;
  22. import java.security.KeyManagementException;
  23. import java.security.KeyStoreException;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.security.cert.CertificateException;
  26. import java.security.cert.X509Certificate;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. public class WebTool2 {
  30. public static void main(String[] args) {
  31. //
  32. String url = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/";
  33. try {
  34. String html = fetchPageContent(url);
  35. List<String> provinces = extractDataByTag(html, "tr", "provincetr");
  36. List<String> cities = extractDataByTag(html, "tr", "citytr");
  37. List<String> counties = extractDataByTag(html, "tr", "countytr");
  38. List<String> towns = extractDataByTag(html, "tr", "towntr");
  39. // 输出提取的数据
  40. System.out.println("Provinces: " + provinces);
  41. System.out.println("Cities: " + cities);
  42. System.out.println("Counties: " + counties);
  43. System.out.println("Towns: " + towns);
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. } catch (Exception e) {
  47. throw new RuntimeException(e);
  48. }
  49. }
  50. private static String fetchPageContent(String url) throws IOException {
  51. // CloseableHttpClient httpClient = HttpClients.createDefault();
  52. HttpGet request = new HttpGet(url);
  53. try {
  54. //忽略https的ssl认证
  55. //发起请求 , 调用trustAll()方法返回的client
  56. HttpEntity entity = trustAll().execute(request).getEntity();
  57. return EntityUtils.toString(entity, "UTF-8");
  58. } catch (Exception e) {
  59. throw new RuntimeException(e);
  60. } finally {
  61. // httpClient.close();
  62. }
  63. }
  64. private static List<String> extractDataByTag(String html, String tagName, String className) {
  65. List<String> dataList = new ArrayList<>();
  66. Document doc = Jsoup.parse(html);
  67. Elements elements = doc.select(String.format(".%s", className));
  68. for (Element element : elements) {
  69. String data = element.select(tagName).text();
  70. dataList.add(data);
  71. }
  72. return dataList;
  73. }
  74. public static CloseableHttpClient trustAll(){
  75. //配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
  76. SSLContext sslContext = null;
  77. try {
  78. sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
  79. @Override
  80. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  81. return true;
  82. }
  83. }).build();
  84. } catch (NoSuchAlgorithmException e) {
  85. e.printStackTrace();
  86. } catch (KeyManagementException e) {
  87. e.printStackTrace();
  88. } catch (KeyStoreException e) {
  89. e.printStackTrace();
  90. }
  91. //创建httpClient
  92. CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
  93. return client;
  94. }
  95. }

2. urlconnection忽略ssl证书连接

忽略HTTPS请求的SSL证书,必须在openConnection之前调用

  1. package com.neo.address.parse;
  2. import java.security.cert.CertificateException;
  3. import java.security.cert.X509Certificate;
  4. import javax.net.ssl.HttpsURLConnection;
  5. import javax.net.ssl.SSLContext;
  6. import javax.net.ssl.TrustManager;
  7. import javax.net.ssl.X509TrustManager;
  8. /**
  9. * Description: httpclient跳过https验证
  10. */
  11. import java.io.OutputStreamWriter;
  12. import java.net.URL;
  13. import java.net.URLConnection;
  14. import javax.net.ssl.HostnameVerifier;
  15. import javax.net.ssl.SSLSession;
  16. import org.apache.commons.io.IOUtils;
  17. /**
  18. * created by liu on 2020/03/18 14:23
  19. */
  20. public class SslUtil {
  21. private static void trustAllHttpsCertificates() throws Exception {
  22. TrustManager[] trustAllCerts = new TrustManager[1];
  23. TrustManager tm = new miTM();
  24. trustAllCerts[0] = tm;
  25. SSLContext sc = SSLContext.getInstance("SSL");
  26. sc.init(null, trustAllCerts, null);
  27. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  28. }
  29. static class miTM implements TrustManager, X509TrustManager {
  30. public X509Certificate[] getAcceptedIssuers() {
  31. return null;
  32. }
  33. public boolean isServerTrusted(X509Certificate[] certs) {
  34. return true;
  35. }
  36. public boolean isClientTrusted(X509Certificate[] certs) {
  37. return true;
  38. }
  39. public void checkServerTrusted(X509Certificate[] certs, String authType)
  40. throws CertificateException {
  41. return;
  42. }
  43. public void checkClientTrusted(X509Certificate[] certs, String authType)
  44. throws CertificateException {
  45. return;
  46. }
  47. }
  48. /**
  49. * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
  50. *
  51. * @throws Exception
  52. */
  53. public static void ignoreSsl() throws Exception {
  54. HostnameVerifier hv = new HostnameVerifier() {
  55. public boolean verify(String urlHostName, SSLSession session) {
  56. System.out.println("Warning: URL Host: " + urlHostName
  57. + " vs. " + session.getPeerHost());
  58. return true;
  59. }
  60. };
  61. trustAllHttpsCertificates();
  62. HttpsURLConnection.setDefaultHostnameVerifier(hv);
  63. }
  64. }

 

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

闽ICP备14008679号