Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Created March 1, 2019 20:17
Show Gist options
  • Save markscottwright/a8252b7a52f7ec0995b2ee3bf1ba0e86 to your computer and use it in GitHub Desktop.
Save markscottwright/a8252b7a52f7ec0995b2ee3bf1ba0e86 to your computer and use it in GitHub Desktop.
How to disable TLS certificate verification in java
package scratch;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*/
public class DisableHttpSecurity {
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException,
KeyManagementException {
URL url = new URL("https://example.com");
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
javax.net.ssl.SSLContext context = javax.net.ssl.SSLContext
.getInstance("TLS");
TrustManager veryTrusting = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
context.init(null, new TrustManager[] { veryTrusting }, null);
connection.setRequestMethod("GET");
connection.setSSLSocketFactory(context.getSocketFactory());
try (var response = connection.getInputStream()) {
System.out.println(new String(response.readAllBytes()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment