I'm trying to connect to WSS websocket using OkHttp3, but I got in onFailure()
method of my WebSocketListener
in particular the Exception said:
javax.net.ssl.SSLHandshakeException: Handshake failed
Now, I'm using this code to connect to WSS
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("wss://mywssdomain").build();
WebSocketListenerCP listener = new WebSocketListenerCP(); //My listener, do nothing only override methods
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
I've read a lot about issue with Android < Lollipop but I'm on Nougat anyway I've tried to nuke all SSL certificate by doing (before connection)
SSLCertificateHandler.nuke();
SSLCertificateHandler class
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSLCertificateHandler {
/**
* Enables https connections
*/
public static void nuke() {
try {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return myTrustedAnchors;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (Exception e) {
}
}
}
And I also tried to add connectionSpecs to my OkHttp3 client
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
.build();
OkHttpClient client = new OkHttpClient.Builder().connectionSpecs(Collections.singletonList(spec)).build();
Request request = new Request.Builder().url("wss://mywssdomain").build();
WebSocketListenerCP listener = new WebSocketListenerCP();
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
I'm not understand
1) Why I get SSLHandshakeException?
2) Is right connection to WSS?