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 2020-05-27 11:46  momingliu11  阅读(6135)  评论(1编辑  收藏  举报