I try to connect to a server with a self-signed certificate. I use this code to accept all certificates.
public class CertificateAcceptor {
public void
The Answer by Prashant may not work, as you need to initialize the SSLContext
as well.
I would do it something like,
SSLSocketFactory sf=null ;
SSLContext sslContext = null;
StringWriter writer;
try {
sslContext = SSLContext.getInstance("TLS") ;
sslContext.init(null,null,null);
} catch (NoSuchAlgorithmException e) {
//<YourErrorHandling>
} catch (KeyManagementException e){
//<YourErrorHandling>
}
try{
sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch(Exception e) {
//<YourErrorHandling>
}
Scheme scheme = new Scheme("https",443,sf);
httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
My issue was, that Java SE 6 or smaller does not support SNI. That means, that one IP can only have one ssl cert. But on my server, there were 3 diffferent apis with different ssl certs. Java SE 7 or greater support SNI and everything worked just fine. (or only running one api on the server)
ALLOW_ALL is not the correct answer. You should set up your certificate with the correct name by using keytool with the ext
extension:
keytool -genkeypair \
-keystore keystore.jks \
-dname "CN=OLEKSIYS-W3T, OU=Sun Java System Application Server, O=Sun Microsystems, L=Santa Clara, ST=California, C=US" \
-keypass changeit \
-storepass changeit \
-keyalg RSA \
-keysize 2048 \
-alias default \
-ext SAN=DNS:localhost,IP:127.0.0.1 \
-validity 9999
See http://tersesystems.com/2014/03/23/fixing-hostname-verification/ for more details.
You may use SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
SSLSocketFactory sf = new SSLSocketFactory(
SSLContext.getInstance("TLS"),
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme sch = new Scheme("https", 443, sf);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet("https://host/");
...
...
Have you tried calling setDefaultHostnameVerifier
of HttpsURLConnection
.
See this link for an example: Accepting a certificate for HTTPs on Android