与OkHttp3的WebSocket连接上的SSLHandshakeException

时间:2018-04-15 08:19:07

标签: java android ssl websocket okhttp3

我尝试使用OkHttp3连接到WSS websocket,但我使用了onFailure()的{​​{1}}方法,特别是Exception说:

  

javax.net.ssl.SSLHandshakeException:握手失败

现在,我使用此代码连接到WSS

WebSocketListener

我已经阅读了很多关于Android<的问题。棒棒糖,但是我还在Nougat上,我试图通过做(在连接之前)来核对所有SSL证书

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();

SSLCertificateHandler类

SSLCertificateHandler.nuke();

我还尝试将connectionSpecs添加到我的OkHttp3客户端

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) {
        }
    }
}

我不明白

1)为什么我会收到SSLHandshakeException?

2)与WSS的连接是否正确?

0 个答案:

没有答案