Websoket 客户端忽略证书验证

一、方法一

<dependency>
	<groupId>org.java-websocket</groupId>
	<artifactId>Java-WebSocket</artifactId>
	<version>1.5.2</version>
</dependency>
package com.neo.websoket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import javax.net.ssl.*;
import java.net.Socket;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 *构建SSLWebSocket客户端,忽略证书
 */
public class SSLWebSocketClient extends WebSocketClient {

    public static void main(String[] args) throws Exception {
        URI serverURI = new URI("wss://124.193.181.178:9781/bvcsp/v1/ws/gpsdata?token=_c9g7HJwCXIYpDq18gcsM03vrB87ZSvJ40HvhXuzlDFv01dQUXEK2kpRm6FnMjR2uDUmt5xZrx9iqqzEi27NxBSTmyME8Y6_GDd3WHJU8kw61uHP1LBj2pAYa67Jgga6F");
        WebSocketClient client = new SSLWebSocketClient(serverURI);
        client.connect();
    }


    //构造方法
    public SSLWebSocketClient(URI serverURI) {
        super(serverURI);
        if(serverURI.toString().contains("wss://")){
            trustAllHosts(this);
            //this.send(message);
        }
    }

    public SSLWebSocketClient(URI serverURI,Draft draft) {
        super(serverURI,draft);
        if(serverURI.toString().contains("wss://"))
            trustAllHosts(this);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("Connected to server");
        // 连接建立后发送消息
        send("{\"all\":true}");
    }

    @Override
    public void onMessage(String message) {
        System.out.println("Received message from server: " + message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Connection closed, code: " + code + ", reason: " + reason);
        // 连接关闭时尝试重新连接
        reconnect();
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("Error occurred: " + ex.getMessage());
        // 出现错误时尝试重新连接
        reconnect();
    }


    /**
     *忽略证书
     *@paramclient
     */
    void trustAllHosts(SSLWebSocketClient client) {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509ExtendedTrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

            }

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                return new java.security.cert.X509Certificate[]{};
//                System.out.println("getAcceptedIssuers");
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                System.out.println("checkClientTrusted");
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                System.out.println("checkServerTrusted");
            }
        }};

        try {

            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, trustAllCerts, new java.security.SecureRandom());

            SSLSocketFactory socketFactory = ssl.getSocketFactory();
            this.setSocketFactory(socketFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、方法二(Spring boot)

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
package cc.oyz.websocket.client;

import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import javax.net.ssl.*;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class CustomWebSocketClient extends StandardWebSocketClient {

    public CustomWebSocketClient() {
        super();

        TrustManager[] trustAllCerts = new TrustManager[]{new X509ExtendedTrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

            }

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                return new java.security.cert.X509Certificate[]{};
//                System.out.println("getAcceptedIssuers");
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                System.out.println("checkClientTrusted");
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                System.out.println("checkServerTrusted");
            }
        }};
        try {
            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, trustAllCerts, new java.security.SecureRandom());
            this.getUserProperties().put(SSLContext.class.getName(),ssl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 /**
     * 位置订阅
     *
     * @return
     */
    @Bean(name = "GpsDataCloudConnectionManager")
    public WebSocketConnectionManager GpsDataCloudConnectionManager() throws Exception {
        WebSocketClient webSocketClient = new CustomWebSocketClient();
        WebSocketConnectionManager manager = new WebSocketConnectionManager(webSocketClient, myWebSocketClientHandler,
                oyzLiveYsConfig.getWebSocketUrl() + "/bvcsp/v1/ws/gpsdata?" + "token=" + ysDeviceService.getYsToken());
        manager.setAutoStartup(true);
        return manager;
    }
posted @ 2024-03-20 19:32  我命由我不由天—hao  阅读(546)  评论(0编辑  收藏  举报