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

运行结果如下:

相关推荐
计算机学姐13 分钟前
基于Python的高校成绩分析管理系统
开发语言·vue.js·后端·python·mysql·pycharm·django
北京_宏哥17 分钟前
《最新出炉》系列入门篇-Python+Playwright自动化测试-50-滚动条操作
python·前端框架·测试
九年义务漏网鲨鱼20 分钟前
【人脸伪造检测后门攻击】 Exploring Frequency Adversarial Attacks for Face Forgery Detection
论文阅读·python·算法·aigc
天冬忘忧34 分钟前
Spark 共享变量:广播变量与累加器解析
大数据·python·spark
小丑西瓜66641 分钟前
MySQL库操作
linux·服务器·数据库·mysql
NK.MainJay1 小时前
Go语言 HTTP 服务模糊测试教程
python·http·golang
荒川之神1 小时前
RHEL/CENTOS 7 ORACLE 19C-RAC安装(纯命令版)
服务器·数据库·oracle
南宫理的日知录1 小时前
106、Python并发编程:深入浅出理解线程池的内部实现原理
开发语言·python·学习·编程学习
萧鼎1 小时前
Python中的随机数生成与控制:random库实战解析
python·random·随机数
三维重建--小博主2 小时前
人群计数制作私有数据集教程-----自用
python·opencv·计算机视觉