python3 urlencode_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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值