python3上post发送json数据

背景:
使用 python 传 json 数据时,假如直接定义变量:

str = {“loginAccount”:“xx”,“password”:“xxx”,“userType”:“individual”}

那实际请求过程中,所传的数据 原本应该是双引号“ 却变成了单引号’:
{‘loginAccount’: ‘xx’, ‘password’: ‘xx’, ‘userType’: ‘individual’}

导致脚本请求报错:
python3上post发送json数据_第1张图片

方法:
引用 json库dumps函数来编码成json格式数据;

json.dumps({“loginAccount”:“xx”,“password”:“xxx”,“userType”:“individual”})

  • json.dumps() 编码成json格式数据
  • json.loads() 对json格式的数据进行解码

例子:

#!/user/bin/python
#-*- coding:utf-8 -*-

import http.client
import json

str = json.dumps({"loginAccount":"xx","password":"xxx","userType":"individual"})
#print(str)

headers = {"Content-type": "application/json","Accept": "*/*"}
conn = http.client.HTTPConnection("131.10.11.102",8002)
conn.request('POST', '/interGateway/v3/user/authentication', str, headers)
response = conn.getresponse()
#print(response.status, response.reason)
data = response.read().decode('utf-8')
print(data)
conn.close()

请求返回:
{“resultStatus”:{“resultCode”:“0000”,“resultMessage”:“登录成功!”,“timeStamp”:“2018-12-12 11:19:29”},“value”:{“loginAccount”:“xx”,“password”:“xxx”,“userId”:“xx”,“token”:“xx”},“exception”:null,“attachments”:{}}

你可能感兴趣的:(python)