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

运行结果如下:

相关推荐
soulteary9 分钟前
突破内存限制:Mac Mini M2 服务器化实践指南
运维·服务器·redis·macos·arm·pika
好看资源平台37 分钟前
网络爬虫——综合实战项目:多平台房源信息采集与分析系统
爬虫·python
爱吃青椒不爱吃西红柿‍️37 分钟前
华为ASP与CSP是什么?
服务器·前端·数据库
进击的六角龙1 小时前
深入浅出:使用Python调用API实现智能天气预报
开发语言·python
檀越剑指大厂1 小时前
【Python系列】浅析 Python 中的字典更新与应用场景
开发语言·python
湫ccc1 小时前
Python简介以及解释器安装(保姆级教学)
开发语言·python
孤独且没人爱的纸鹤1 小时前
【深度学习】:从人工神经网络的基础原理到循环神经网络的先进技术,跨越智能算法的关键发展阶段及其未来趋势,探索技术进步与应用挑战
人工智能·python·深度学习·机器学习·ai
羊小猪~~1 小时前
tensorflow案例7--数据增强与测试集, 训练集, 验证集的构建
人工智能·python·深度学习·机器学习·cnn·tensorflow·neo4j
lzhlizihang1 小时前
python如何使用spark操作hive
hive·python·spark
q0_0p1 小时前
牛客小白月赛105 (Python题解) A~E
python·牛客