【Java】+ 【wss】 + WebSocketClient

一、maven依赖

备注:maven仓库官方(https://mvnrepository.com/

        <!--        WebSocket start-->
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--        WebSocket end-->

 

二、工具(可直接复制使用)

备注:类(ZgxWssUtil)

package com.wss;

import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;

/**
 * @author :Jarvis
 * @version :v1.0
 * @date :2020-04-14 20:45
 */
abstract class ZgxWssUtil extends WebSocketClient {

    public ZgxWssUtil(URI serverURI) {
        super(serverURI);
        if (serverURI.toString().contains("wss://"))
            trustAllHosts(this);
    }

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

    public ZgxWssUtil(URI serverURI, Draft draft, Map<String, String> headers, int connecttimeout) {
        super(serverURI, draft, headers, connecttimeout);
        if (serverURI.toString().contains("wss://"))
            trustAllHosts(this);
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };


    static void trustAllHosts(ZgxWssUtil appClient) {
        System.out.println("start...");
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }
        }};

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            appClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

三、使用工具进行wss协议的接口请求

备注:类(WssTest)

package com.wss;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.*;

/**
 * @author :Jarvis
 * @version :v1.0
 * @date :2020-04-14 20:49
 */
public class WssTest {
    public static List<String> result = new ArrayList<>();
    public static String initmsg = "{'cmd':'login','data':{'username':'xinji','password':'PASSWORD'}}"
            .replaceAll("'", "\"").replaceAll("PASSWORD", "1402");

    public static void main(String[] args) throws URISyntaxException {
        Map<String, String> headers = new HashMap<>();
        headers.put("Sec-WebSocket-Extensions", "permessage-deflate; client_max_window_bits");
        headers.put("Sec-WebSocket-Key", "leYVDOk73PPvYNT+O5toQA==");
        headers.put("Sec-WebSocket-Protocol", "x-access-token, eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODczOTIzOTQsImlkIjo0LCJ0b2tlbiI6IjY4NmI1OTQxNTU2ZTQxNGE2ZDc0NmE2NyJ9.8n9ygZd0Xg1-iWLusoFMaieXi4DvVgwkwt-r1tKJmkQ");
        headers.put("Sec-WebSocket-Version", "13");
        // 以下请求头可以不用传
//        headers.put("Connection", "Upgrade");
//        headers.put("Upgrade", "websocket");
//        headers.put("Accept-Encoding", "gzip, deflate, br");
//        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
//        headers.put("Cache-Control", "no-cache");
//        headers.put("Host", "cloud.iotsquare.xyz");
//        headers.put("Origin", "https://cloud.iotsquare.xyz");
//        headers.put("Pragma", "no-cache");
//        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36");

        Draft draft = new Draft_17();
        draft.setParseMode(WebSocket.Role.CLIENT);
        new ZgxWssUtil(new URI("wss://*****************填写自己的url*******************************")
                , draft
                , headers
                , 10
        ) {

            @Override
            public void onClose(int arg0, String arg1, boolean arg2) {
                System.out.println(String.format("onClose:【%s】【%s】【%s】", arg0, arg1, arg2));
            }

            @Override
            public void onError(Exception arg0) {
                System.out.println(String.format("onError:%s", arg0));

            }

            @Override
            public void onMessage(String arg0) {
                if (!arg0.equals("pong")) {
                    result.add(arg0);
                    System.out.println(String.format("onMessage:%s", arg0));
                }
                this.send(arg0);
            }

            @Override
            public void onOpen(ServerHandshake arg0) {
                System.out.println(String.format("onOpen:%s", arg0));
                this.send(initmsg);
            }
        }.connect();
    }
}

 

四、结果

4.1、打印结果

 

 

4.2、浏览器控制台查看结果

 

posted @ 2020-04-15 00:22  淡怀  阅读(7580)  评论(2编辑  收藏  举报