Skip to content

Instantly share code, notes, and snippets.

@mingliangguo
Last active August 21, 2023 11:47
Show Gist options
  • Save mingliangguo/c86e05a0f8a9019b281a63d151965ac7 to your computer and use it in GitHub Desktop.
Save mingliangguo/c86e05a0f8a9019b281a63d151965ac7 to your computer and use it in GitHub Desktop.
disable SSL and host name verification for apache httpclient
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sc).build();
String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
.connectTimeout(1000)
.socketTimeout(1000)).returnContent().asString();
} catch (Exception e) {
}
# source: http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0
// update on March 2022, the following is a much simpler version to disable the SSL check with Apache httpclient
var httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
@ugifractal
Copy link

thanks

working nicely..

@nikoskip
Copy link

You are my f*** hero!

@Artur-at-work
Copy link

Artur-at-work commented May 2, 2020

Thanks for sharing.
I had warning that setSslcontext(sc) was deprecated. So had to add one line to make it work:

@SuppressWarnings("deprecation")
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();

@andrepra
Copy link

From documentation

setSslcontext(SSLContext sslcontext)
Deprecated. (4.5) use setSSLContext(SSLContext)

@anvesh-kenguva
Copy link

This helps a lot, Thanks

@AL3X-69
Copy link

AL3X-69 commented Aug 11, 2021

Thanks, you saved my day

@sarah502
Copy link

I love you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment