JAVA访问https网站如何跳过验证

转自:https://blog.csdn.net/chancein007/article/details/74157144

在Java的编程世界里面,我们有的时候,会经常访问一些HTTPS的网站,那么访问这些HTTPS的网站的时候,如果当前这个网站是自己企业内部的已知 的网站,或者我们信任的网站,这个时候,我们为了编写程序的方便,就不需要把当前网站的服务器的根证书以及中间证书导入到JKS里面,让在程序在调用HTTP协议的时候对服务器的服务器名和证书名进行对比。说了这么多,那么应该如何做呢?其实也挺简单的,请看下面的Java代码。

在类的开头加入一段static的代码

static 
  {
    try
    {
      trustAllHttpsCertificates();
      HttpsURLConnection.setDefaultHostnameVerifier
      (
        new HostnameVerifier() 
        {
          public boolean verify(String urlHostName, SSLSession session)
          {
            return true;
          }
        }
      );
    } catch (Exception e)  {}
  }

trustAllHttpsCertificates()方法的实现

 private static void trustAllHttpsCertificates() 
    throws NoSuchAlgorithmException, KeyManagementException
  {
    TrustManager[] trustAllCerts = new TrustManager[1]; 
    trustAllCerts[0] = new TrustAllManager(); 
    SSLContext sc = SSLContext.getInstance("SSL"); 
    sc.init(null, trustAllCerts, null); 
    HttpsURLConnection.setDefaultSSLSocketFactory(
        sc.getSocketFactory());
  }
 
  private static class TrustAllManager 
    implements X509TrustManager 
  {
    public X509Certificate[] getAcceptedIssuers() 
    {
      return null;
    } 
    public void checkServerTrusted(X509Certificate[] certs, 
        String authType)
      throws CertificateException 
    {
    } 
    public void checkClientTrusted(X509Certificate[] certs, 
        String authType)
    throws CertificateException 
    {
    }
  }

猜你喜欢

转载自blog.csdn.net/weixin_43408956/article/details/88825411