HttpURLConnection忽略https认证

 public static Bitmap getBitmapFromURL(String src) {
    try {
      URL url = new URL(src);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      boolean useHttps = src.startsWith("https");
      if (useHttps) {
        HttpsURLConnection https = (HttpsURLConnection) connection;
        trustAllHosts(https);
        https.setHostnameVerifier(DO_NOT_VERIFY);
      }


      connection.setDoInput(true);
      connection.connect();
      InputStream input = connection.getInputStream();
      return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
      return null;
    }
  }

  /**
   * 覆盖java默认的证书验证
   */
  private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
      return new java.security.cert.X509Certificate[]{};
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }
  }};

  /**
   * 设置不验证主机
   */
  private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  };

  /**
   * 信任所有
   * @param connection
   * @return
   */
  private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      SSLSocketFactory newFactory = sc.getSocketFactory();
      connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return oldFactory;
  }

参考文章:https://blog.csdn.net/u012527802/article/details/70172357

你可能感兴趣的:(HttpURLConnection忽略https认证)