首页 > 其他分享 >Websoket 客户端忽略证书验证

Websoket 客户端忽略证书验证

时间:2024-03-20 19:45:26浏览次数:24  
标签:Websoket java String 证书 void X509Certificate Override public 客户端

一、方法一

<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 one rror(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;
    }

标签:Websoket,java,String,证书,void,X509Certificate,Override,public,客户端
From: https://www.cnblogs.com/haolb123/p/18085921

相关文章

  • 1+x成绩查询及职业技能等级证书下载,超详细!!!
    操作步骤点击官网链接https://vslc.ncb.edu.cn/gateway/Querydata成绩查询:证件号码和准考证号都是身份证号码证书查询:输入身份证号和准考证号,或访问【学分银行平台】进行查询:登录—我的成果—查看小提示:登录账号是身份证号,密码为身份证号后6位。......
  • redis的客户端操作,使用场景
    ####配置允许远程链接############1使用配置文件启动redisdaemonizeyesbind0.0.0.0protected-modenorequirepass123456pidfile/var/run/redis.pidport6379dir"/root/redis-7.2.4/data"logfile6379.log#2redis-server./redis-conf#3允许远程链接......
  • Java调用python服务接口https遇到证书问题的具体解决
    是这样的,大概前一段时间做过一个业务,一直没有记录下来就是我们的算法部,封装好了一系列的算法,然后是python写的。而我们需要用Java去调用他们的方法。如何处理这个问题呢就是我在python里面写了一个rest-api,暴露出几个接口,供Java这边调。但是不知道为什么算法部当时那边弄了个......
  • 【开发环境搭建篇】Redis客户端安装和配置
    作者介绍:本人笔名姑苏老陈,从事JAVA开发工作十多年了,带过大学刚毕业的实习生,也带过技术团队。最近有个朋友的表弟,马上要大学毕业了,想从事JAVA开发工作,但不知道从何处入手。于是,产生了写一个博客专栏想法,介绍当前互联网企业JAVA项目开发如何快速入门。本文收录于《30天企......
  • tomcat采集阿里云slb真实客户端ip
    tomcat采集阿里云slb真实客户端ip......
  • 邮件客户端的配置使用
    软件介绍:winmail收到新邮件不会提示用户,这样用户就容易错过消息下载foxmail可以解决这个问题一:下载foxmail1.实体机进入官网https://www.foxmail.com/,点击下载版本随意下载好后拖到虚拟机上二:配置foxmail1.开始创建账号因为这几种邮箱都不是我们上个实验的邮箱选择其他邮......
  • 自动申请和部署SSL证书
    背景使用国人开发的软件,实现SSL证书的自动申请和部署,网址:https://gitee.com/certd/certd后记在上述软件的主页,描述的非常清楚。下边就贴一下docker-compose.yml文件:version:'3.3'services:certd:#镜像#↓↓......
  • 【Lazy ORM】 小工具 acw 本地客户端 你负责点击页面,他负责输出代码
    介绍wu-smart-acw-client简称acw-client,是一个基于LazyORM定制的客户端代码生成小工具LazyORM小工具acw本地客户端你负责点击页面,他负责输出代码安装<dependency><groupId>top.wu2020</groupId><artifactId>wu-smart-acw-cli......
  • 好用的Redis 客户端工具有几个? 这里推荐两三个
    微信公众号:数据库杂记   个人微信: iiihero我是iihero. 也可以叫我Sean.iihero@CSDN(https://blog.csdn.net/iihero) Sean@墨天轮 (https://www.modb.pro/u/16258)数据库领域的资深爱好者一枚。水木早期数据库论坛发起人 db2@smth,早期多年水木论坛数据库版版主。......
  • 详解SSL证书系列(5)SSL证书为什么不能好多年签一次呢
    上一篇介绍了详解SSL证书系列(4)免费的SSL证书和收费的证书有什么区别,这一篇我们继续了解一下我们申请的SSL证书为什么不能好多年签一次呢,这样不是更省事吗?SSL证书最多只能签发一年,一年到期后需要续签。至于为什么不能一次性签发多年的,最主要的原因是从安全角度来考虑的。以自......