在 Java 中使用-Djavax.net.ssl.trustAllCerts=true
和-Djavax.net.ssl.trustStoreType=JKS
等 JVM 参数可以在一定程度上绕过证书检查,但这种方式是不安全的,不建议在生产环境中使用。并且这种方式并不是使用 “no--check--certificate” 这样的表述。
以下是一个示例代码片段,但请注意这只是为了演示目的,实际应用中应谨慎使用:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class NoCertificateCheckExample {
public static void main(String[] args) {
try {
URL url = new URL("https://your-url-with-invalid-certificate.com");
URLConnection connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
// 忽略证书验证
trustAllHosts(httpsConnection);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine())!= null) {
System.out.println(line);
}
}
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
private static void trustAllHosts(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}}, new SecureRandom());
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
}