Signalr 解决https Trust anchor for certification path not found.问题

最近在使用Signalr 进行websocket 连接。测试服务是Http,Connect可以成功,但是切到线上环境Https,连接失败。

Error:

image

修改后代码:增加Https 忽略证书

/*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
See License.txt in the project root for license information.
*/

package com.github.signalr4j.client.transport;

import com.github.signalr4j.client.ConnectionBase;
import com.github.signalr4j.client.LogLevel;
import com.github.signalr4j.client.Logger;
import com.github.signalr4j.client.Platform;
import com.github.signalr4j.client.SignalRFuture;
import com.github.signalr4j.client.UpdateableCancellableFuture;
import com.github.signalr4j.client.http.HttpConnection;
import com.google.gson.Gson;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.util.Charsetfunctions;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Implements the WebsocketTransport for the Java SignalR library Created by
 * stas on 07/07/14.
 */
public class WebsocketTransportNew extends HttpClientTransport {

    private static final String HTTP_SCHEME = "http";
    private static final String SECURE_HTTP_SCHEME = "https";

    private static final String WEBSCOCKET_SCHEME = "ws";
    private static final String SECURE_WEBSOCKET_SCHEME = "wss";

    private static final String HTTP_URL_START = HTTP_SCHEME + "://";
    private static final String SECURE_HTTP_URL_START = SECURE_HTTP_SCHEME + "://";

    private static final String WEBSOCKET_URL_START = WEBSCOCKET_SCHEME + "://";
    private static final String SECURE_WEBSOCKET_URL_START = SECURE_WEBSOCKET_SCHEME + "://";
    private static final Gson gson = new Gson();
    WebSocketClient mWebSocketClient;
    private String mPrefix;
    private UpdateableCancellableFuture mConnectionFuture;

    public WebsocketTransportNew(Logger logger) {
        super(logger);
    }

    public WebsocketTransportNew(Logger logger, HttpConnection httpConnection) {
        super(logger, httpConnection);
    }

    @Override
    public String getName() {
        return "webSockets";
    }

    @Override
    public boolean supportKeepAlive() {
        return true;
    }

    @Override
    public SignalRFuture start(final ConnectionBase connection, ConnectionType connectionType,
                                     final DataResultCallback callback) {

        final String connectionUrl = connection.getUrl()
                .replace(HTTP_URL_START, WEBSOCKET_URL_START)
                .replace(SECURE_HTTP_URL_START, SECURE_WEBSOCKET_URL_START);

        final String connectionString = connectionType == ConnectionType.InitialConnection ? "connect" : "reconnect";
        boolean isSsl = false;

        String url = connectionUrl + connectionString
                + TransportHelper.getReceiveQueryString(this, connection);

        if (connection.getQueryString() != null) {
            url += "&" + connection.getQueryString();
        }

        if (url.startsWith(SECURE_WEBSOCKET_SCHEME)) {
            isSsl = true;
        }

        mConnectionFuture = new UpdateableCancellableFuture(null);

        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            mConnectionFuture.triggerError(e);
            return mConnectionFuture;
        }

        mWebSocketClient = new WebSocketClient(uri, new Draft_6455(), connection.getHeaders(), 0) {

            Exception e;

            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                mConnectionFuture.setResult(null);
            }

            @Override
            public void onMessage(String s) {
                callback.onData(s);
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                mWebSocketClient.close();
                if (i != CloseFrame.NORMAL || e != null) {
                    connection.onError(e, true);
                }
            }

            @Override
            public void onError(Exception e) {
                mWebSocketClient.close();
                this.e = e;
            }

            @Override
            public void onFragment(Framedata frame) {
                try {
                    String decodedString = Charsetfunctions.stringUtf8(frame.getPayloadData());

                    if (decodedString.equals(",")) {
                        return;
                    }

                    if (decodedString.equals("]}")) {
                        return;
                    }

                    if (decodedString.endsWith(":[") || null == mPrefix) {
                        mPrefix = decodedString;
                        return;
                    }

                    String simpleConcatenate = mPrefix + decodedString;

                    if (isJSONValid(simpleConcatenate)) {
                        onMessage(simpleConcatenate);
                    } else {
                        String extendedConcatenate = simpleConcatenate + "]}";
                        if (isJSONValid(extendedConcatenate)) {
                            onMessage(extendedConcatenate);
                        } else {
                            log("invalid json received:" + decodedString, LogLevel.Critical);
                        }
                    }
                } catch (InvalidDataException e) {
                    e.printStackTrace();
                }
            }
        };

        if (isSsl) {
            // Create a trust manager that does not validate certificate chains
            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) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }
            }};
            SSLContext sc = null;
            try {
                sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
//            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocketFactory factory = sc.getSocketFactory();
            try {
                mWebSocketClient.setSocket(factory.createSocket());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        mWebSocketClient.connect();

        connection.closed(new Runnable() {
            @Override
            public void run() {
                mWebSocketClient.close();
            }
        });

        return mConnectionFuture;
    }

    private String encodeValue(String value) {

        String result = "";

        try {
            if (value != null) {
                result = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    private Socket createConnectedSocket(URI uri) throws IOException {
        String host = uri.getHost();
        boolean isSecureSocket = uri.toString().startsWith(SECURE_WEBSOCKET_URL_START);
        int port = isSecureSocket ? 443 : 80;

        boolean useProxy = Platform.useProxy();
        String proxyHost = Platform.getProxyHost();
        int proxyPort = Platform.getProxyPort();
        Proxy proxy = useProxy ? new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort))
                : Proxy.NO_PROXY;

        if (isSecureSocket) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            if (useProxy) {
                Socket underlyingSocket = new Socket(proxy);
                underlyingSocket.connect(new InetSocketAddress(host, port), CONNECTION_TIMEOUT_MS);
                return factory.createSocket(underlyingSocket, proxyHost, proxyPort, true);
            } else {
                Socket socket = factory.createSocket();
                socket.connect(new InetSocketAddress(host, port), CONNECTION_TIMEOUT_MS);
                return socket;
            }
        } else {
            Socket socket = new Socket(proxy);
            socket.connect(new InetSocketAddress(host, port), CONNECTION_TIMEOUT_MS);
            return socket;
        }
    }

    @Override
    public SignalRFuture send(ConnectionBase connection, String data, DataResultCallback callback) {
        mWebSocketClient.send(data);
        return new UpdateableCancellableFuture(null);
    }

    private boolean isJSONValid(String test) {
        try {
            gson.fromJson(test, Object.class);
            return true;
        } catch (com.google.gson.JsonSyntaxException ex) {
            return false;
        }
    }
}

主要修改代码是在
if (isSsl) {
//代码
}

你可能感兴趣的:(Signalr 解决https Trust anchor for certification path not found.问题)