https绕过证书

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import java.security.SecureRandom;

public class HttpUtil {
    public static HttpURLConnection getHttpURLConnection(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (url.getProtocol().equalsIgnoreCase("https")) {
            SSLContext sc = null;
            try {
                sc = SSLContext.getInstance("TLS");
                sc.init(null, new TrustManager[]{new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }}, new SecureRandom());
            } catch (Exception e) {}
            if (sc != null) {
                conn.setSSLSocketFactory(sc.getSocketFactory());
            }
        }
        return conn;
    }
}

该方法检查 URL 是否使用 HTTPS 协议。如果是,它将创建一个 SSLContext 对象并使用一个自定义的 X509TrustManager,该 X509TrustManager 接受所有 SSL 证书。然后,它将使用 SSLContext 对象配置 HttpURLConnection,绕过 HTTPS 证书验证。如果 URL 使用 HTTP 协议,则返回 HttpURLConnection 对象。

您可以使用以下代码调用该方法:

HttpURLConnection conn = HttpUtil.getHttpURLConnection("https://www.example.com");
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int responseCode = conn.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

Q.E.D.