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

运行结果如下:

相关推荐
梧桐树042910 分钟前
python常用内建模块:collections
python
Dream_Snowar18 分钟前
速通Python 第三节
开发语言·python
远游客071323 分钟前
centos stream 8下载安装遇到的坑
linux·服务器·centos
蓝天星空2 小时前
Python调用open ai接口
人工智能·python
jasmine s2 小时前
Pandas
开发语言·python
郭wes代码2 小时前
Cmd命令大全(万字详细版)
python·算法·小程序
leaf_leaves_leaf2 小时前
win11用一条命令给anaconda环境安装GPU版本pytorch,并检查是否为GPU版本
人工智能·pytorch·python
夜雨飘零12 小时前
基于Pytorch实现的说话人日志(说话人分离)
人工智能·pytorch·python·声纹识别·说话人分离·说话人日志
404NooFound2 小时前
Python轻量级NoSQL数据库TinyDB
开发语言·python·nosql
LIKEYYLL2 小时前
GNU Octave:特性、使用案例、工具箱、环境与界面
服务器·gnu