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)


版权声明:本文为weixin_39927508原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。