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())

运行结果如下:

相关推荐
Flittly12 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling16 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook20 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风21 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风21 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei2 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm