Authentication
认证方式
python实现
import requests
from requests.auth import HTTPDigestAuth
from ws4py.client.threadedclient import WebSocketClient
import json
import xmltodict
def xml_to_json(xml_str):
# parse是的xml解析器
xml_parse = xmltodict.parse(xml_str)
# json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
# dumps()方法的ident=1,格式化json
json_str = json.dumps(xml_parse, indent=1)
return json_str
class EchoClient(WebSocketClient):
def opened(self):
print("Web socket连接已建立")
def closed(self, code, reason):
print(("Closed down", code, reason))
def received_message(self, m):
print("=> %d %s" % (len(m), str(m)))
# 设置登录用户和密码
digest_auth = HTTPDigestAuth('Default User', 'robotics')
# 设置Post的Header
content_header = {'Content-Type': 'application/x-www-form-urlencoded;v=2.0'}
# 设置订阅的地址
subscription_url = 'http://127.0.0.1:80/subscription?json=1'
# 设置订阅的Resources
payload = {'resources': ['1', '2'], # 订阅的第一组信号
# 订阅的资源信息 马达指示灯状态 切换到手动模式后会闪烁
'1': '/rw/iosystem/signals/Local/DRV_1/MOTLMP;state',
'1-p': '1', # 订阅的资源的优先级 这里是Medinum
'2': '/rw/panel/opmode', # 订阅了手自动信息
'2-p': '1'
}
# 申明session
session = requests.Session()
# 进行Post操作
resp = session.post(subscription_url, auth=digest_auth, headers=content_header, data=payload, verify=False)
# 如果接受成功
if resp.status_code == 201:
print(resp.text)
# 读取连接的地址
location = resp.headers['Location']
print(resp.cookies['-http-session-'])
print(resp.cookies['ABBCX'])
# 设置cookie
cookie = '-http-session-={0}; ABBCX={1}'.format(resp.cookies['-http-session-'], resp.cookies['ABBCX'])
header = [('Cookie', cookie)]
print(" resp header :", header)
print("ws 地址:", location)
'''
Cookie: -http-session-=15::http.session::3a7164f8f3668128db7724dc5a680d2c; ABBCX=24
'''
ws = EchoClient(location , protocols=['robapi2_subscription'], headers=header)
ws.connect()
ws.run_forever()
闭坑
# 鉴权为 DigestAuth
digest_auth = HTTPDigestAuth('Default User', 'robotics')
# 子协议为 robapi2_subscription
ws = EchoClient(location , protocols=['robapi2_subscription'], headers=header)
Postman
Subscriptions
webSocket
Websocket 子协议应配置为robapi2_subscription
websocket = new WebSocket('ws://127.0.0.1:80', ['robapi2_subscription']);
// 添加监听打开事件
websocket.addEventListener('open', function (event) {
console.log('ws 连接...');
});
// 添加监听接收 事件
websocket.addEventListener('message', function (event) {
console.log('服务器消息: ', event.data);
});