随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

Python3下urllib.parse.urlencode()编码

 

zabbix_url="http://10.10.2.2/zabbix/api_jsonrpc.php"
headers = {'Content-Type':'application/json'}
auth_data = {
"jsonrpc":"2.0",
"method":"user.login",
"id":0
}


urllib.parse.urlencode() 不能对string编码,只能对dict类型编码
urllib.parse.urlencode() #将dict类型参数转化为query_string格式(key=value&key=value),并且将中文转码,最终会转换为bytes(字节流)类型,如下:
query_string = urllib.parse.urlencode(auth_data).encode('utf8')
query_string为bytes类型,格式如:b'jsonrpc=2.0&method=user.login&id=0'


#如果服务器端要求传递json格式数据,则先用json.dumps() 将dict参数先转换为str,然后再使用bytes()将其转换为bytes(字节流)类型,如下:
#json.loads() transform str to dict;json.dumps() transform dict to str
query_string = bytes(json.dumps(auth_data),'utf8')
query_string为bytes类型,格式如:b'{"jsonrpc": "2.0", "method": "user.login"}


#urllib.request.Request()要求传递的data为bytes(字节流)类型
request = urllib.request.Request(zabbix_url,query_string,headers=headers)
reponse = urllib.request.urlopen(request).read()
content = json.loads(reponse.decode('utf8'))
print(content)

 

posted on   momingliu11  阅读(6198)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2016-05-27 多进程、多线程处理文件对比
2016-05-27 大文件拆分
2014-05-27 读取xml格式文件
2013-05-27 Network Monitor
2013-05-27 循环while、foreach-object
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示