Created
November 29, 2012 17:19
-
-
Save michalbcz/4170520 to your computer and use it in GitHub Desktop.
java - https url connection - trust any certificate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URL; | |
import java.security.SecureRandom; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import javax.net.ssl.HostnameVerifier; | |
import javax.net.ssl.HttpsURLConnection; | |
import javax.net.ssl.KeyManager; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.SSLSession; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
/* | |
Found on http://stackoverflow.com/questions/7684654/how-to-make-apache-commons-httpclient-3-1-ignore- https-certificate-invalidity and copy pasted from working sample in answer http://stackoverflow.com/a/7684887 | |
*/ | |
public class SSLTest { | |
public static void main(String [] args) throws Exception { | |
// configure the SSLContext with a TrustManager | |
SSLContext ctx = SSLContext.getInstance("TLS"); | |
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); | |
SSLContext.setDefault(ctx); | |
URL url = new URL("https://mms.nw.ru"); | |
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); | |
conn.setHostnameVerifier(new HostnameVerifier() { | |
@Override | |
public boolean verify(String arg0, SSLSession arg1) { | |
return true; | |
} | |
}); | |
System.out.println(conn.getResponseCode()); | |
conn.disconnect(); | |
} | |
private static class DefaultTrustManager implements X509TrustManager { | |
@Override | |
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} | |
@Override | |
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
} | |
} |
The properties should be set PER CONNECTION and NEVER globally!
(the same happens with Authenticator.setDefault)
These methods should be available only for debug purposes...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks .. but didn't work for me on jenkins