Socket.io client in android connection with HTTPS

2019-03-31 13:51发布

问题:

io on server and client on android.

It results in connection error on android as long as I enable HTTP(S) SSL(works fine if disable it however)

I've tried to implement HTTPS connection on Android, took reference from sample on Github as following:

opts = new IO.Options();
opts.sslContext = mySSLContext;
opts.hostnameVerifier = myHostnameVerifier;
socket = IO.socket("https://mychat.url", opts);

also this

SSLContext mySSLContext = SSLContext.getInstance("TLS");
mySSLContext.init(null, null, null);

and this

myHostnameVerifier = new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
});

Still got error message during socket transport

io.socket.engineio.client.EngineIOException: xhr poll error

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

What does it take to fulfill socket io connection with HTTPS protocol?

回答1:

Thanks to @Apurva I resolve it on my own.

Seems that TrustManager is necessary to initialize sslContext

so I added

mySSLContext.init(null, trustAllCerts, null);

with parameter trustAllCerts refer to

private final TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[] {};
    }

    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }
} };

And finally connected to chat server successfully.