Python实现websocket连接服务器报rejected WebSocket connection: HTTP 401

1. websockets报HTTP 401解决办法

代码如下:

python 复制代码
#!/usr/bin/env python
import asyncio
import websockets
import requests

uri = 'ws://192.168.20.167/websocket'
msg = '''{"type":6,"param":{"businessType":3,"cmd":1,"frequency":200}}'''

def login():
    log_data_dic = {"userName": 'admin', "password": 'admin', "rememberMe": 0}
    header = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    login_url = 'http://192.168.20.167/login'
    session = requests.Session()
    response = session.post(login_url, data=log_data_dic, headers=header)
    print('response = ', response)

async def test():
    login()
    async with websockets.connect(uri) as websocket:
        await websocket.send(msg)
        while True:
            response = await websocket.recv()
            print('response = ', response)
            
asyncio.run(test())

执行后报如下错误:

解决办法:连接服务器时带上cookie,代码如下:

python 复制代码
#!/usr/bin/env python
import asyncio
import websockets
import requests

def login():
    log_data_dic = {"userName": 'admin', "password": 'admin', "rememberMe": 0}
    header = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    login_url = 'http://192.168.20.167/login'
    session = requests.Session()
    response = session.post(login_url, data=log_data_dic, headers=header)
    cookie = response.cookies
    print('cookie = ', cookie)
    return cookie

async def test():
    cookie = login()
    uri = 'ws://192.168.20.167/websocket'
    msg = '''{"type":6,"param":{"businessType":3,"cmd":1,"frequency":200}}'''
    async with websockets.connect(uri, extra_headers={'Cookie':cookie}) as websocket:
        await websocket.send(msg)
        while True:
            response = await websocket.recv()
            print('response = ', response)

asyncio.run(test())

运行结果:

2. websocket报HTTP 401解决办法

代码如下:

python 复制代码
#!/usr/bin/env python
import asyncio
import websocket
import requests

uri = 'ws://192.168.20.167/websocket'
msg = '''{"type":6,"param":{"businessType":3,"cmd":1,"frequency":200}}'''

def login():
    log_data_dic = {"userName": 'admin', "password": 'admin', "rememberMe": 0}
    header = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    login_url = 'http://192.168.20.167/login'
    session = requests.Session()
    response = session.post(login_url, data=log_data_dic, headers=header)
    cookies = response.cookies.get_dict()
    access_token = cookies.get('access_token')
    cookie = f'access_token={access_token}'
    return cookie

async def test():
    cookie = login()
    cookie = f'{cookie}; userName=admin; role=ADMIN; isAuthenticated=true; devType=ue'
    ws = websocket.WebSocket()
    ws.connect(uri)
    ws.send(msg)
    while True:
        ret = ws.recv()
        print(ret)

asyncio.run(test())

解决办法:连接服务器是带上cookie,代码如下:

python 复制代码
#!/usr/bin/env python
import asyncio
import websocket
import requests

uri = 'ws://192.168.20.167/websocket'
msg = '''{"type":6,"param":{"businessType":3,"cmd":1,"frequency":200}}'''

def login():
    log_data_dic = {"userName": 'admin', "password": 'admin', "rememberMe": 0}
    header = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    login_url = 'http://192.168.20.167/login'
    session = requests.Session()
    response = session.post(login_url, data=log_data_dic, headers=header)
    cookies = response.cookies.get_dict()
    access_token = cookies.get('access_token')
    cookie = f'access_token={access_token}'
    return cookie

async def test():
    cookie = login()
    cookie = f'{cookie}; userName=admin; role=ADMIN; isAuthenticated=true; devType=ue'
    ws = websocket.WebSocket()
    ws.connect(uri, cookie=cookie)
    ws.send(msg)
    while True:
        ret = ws.recv()
        print(ret)

asyncio.run(test())

运行结果如下:

相关推荐
龙泉寺天下行走几秒前
LangChain Skills框架核心解析
python·langchain·aigc
echome8882 分钟前
Python 装饰器详解:从入门到精通的实用指南
开发语言·python
tang777897 分钟前
爬虫代理IP池到底有啥用?
网络·爬虫·python·网络协议·tcp/ip·ip
sg_knight10 分钟前
设计模式实战:享元模式(Flyweight)
python·设计模式·享元模式·flyweight
墨有66612 分钟前
基于弦论流体对偶与环空间约化的湍流精确数值模型
python·流体力学·弦理论
原来是猿15 分钟前
Linux - 基础IO【下】
linux·运维·服务器
兰文彬29 分钟前
n8n 2.x版本没有内嵌Python环境
开发语言·python
smileNicky1 小时前
Spring AI系列之对话记忆与工具调用指南
人工智能·python·spring
飞Link1 小时前
深度解析 TS2Vec:时序表示学习中的层次化建模(Hierarchical Contrastive Learning)
开发语言·python·学习·数据挖掘
代码探秘者1 小时前
【Java集合】ArrayList :底层原理、数组互转与扩容计算
java·开发语言·jvm·数据库·后端·python·算法