今天研究一个接口,post请求,application/x-www-form-urlencoded格式 --表单形式提交
1、application/x-www-form-urlencoded
1)浏览器的原生form表单
2) 提交的数据按照 key1=val1&key2=val2 的方式进行编码,key和val都进行了URL转码
POST [http://www.example.com](http://www.example.com) HTTP/1.1
Content-Type: application/x-[www-form-urlencoded](http://www-form-urlencoded);charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
2. 接口相关内容:
fiddler抓包,
postman正常请求成功,fiddler抓包,参数如上所示;raw 中可看到,已 进行了 转码
python代码如下:
urlq = "http://xx.xx.xx.xxx:xxxx/ncmisservice/contract/creditContract/callbackYZ"
headers = {"Content-Type":"application/x-www-form-urlencoded"}
data = {
"serno": "10000320042201578",
"prdCode": "YGYZD",
"contracts": [{
"pdfFileId": "b4f1b909ba4711e982ec00163e0cdd78",
"signDt": "2019-08-26 15:18:22",
"contractName": "xxxx授信合同",
"contNo": "30010320042201133",
"contTyp": "01"
}],
"legalInfo": {
"legalPhone": "15810145528",
"openingBank": "招商银行",
"cardNumber": "23423423647",
"bankMobileNumber": "15810145528"
}
}
data['serno'] = '10000320120338114'
data['contracts'][0]['contNo'] = '3'
#youzanShouxinContract = json.dumps(youzanShouxinContract)
redata = {
"serviceId":'contractsInfo',
"data": data
}
redata = json.dumps(redata) #dict 转成 json
print(type(redata),redata)
re = requests.post(url=urlq, headers=headers, data=redata)
但是发现不通。通过fiddler抓包,参数如下:
代码一直不通,一直给错误提示,如下:
一直在提示 必填字符data 不存在。无论是将data单独转成json 字符串,还是redata整体转成json 字符串,都不行。
知识点:dict 字典转json字符串:redata = json.dumps(redata)
后来,终于找到了一种可以的。 redata整体进行转义:redata = urlencode(redata) ---关键点
代码如下:
from urllib.parse import urlencode
urlq = "http://xx.xx.xx.xxx:xxxx/ncmisservice/contract/creditContract/callbackYZ"
headers = {"Content-Type":"application/x-www-form-urlencoded"}
data = {
"serno": "10000320042201578",
"prdCode": "YGYZD",
"contracts": [{
"pdfFileId": "b4f1b909ba4711e982ec00163e0cdd78",
"signDt": "2019-08-26 15:18:22",
"contractName": "xxxx贷授信合同",
"contNo": "30010320042201133",
"contTyp": "01"
}],
"legalInfo": {
"legalPhone": "15810145528",
"openingBank": "招商银行",
"cardNumber": "23423423647",
"bankMobileNumber": "15810145528"
}
}
data['serno'] = '10000320120338114'
data['contracts'][0]['contNo'] = '3'
redata = {
"serviceId":'contractsInfo',
"data": data
}
redata = urlencode(redata) #key关键点
print(type(redata),redata)
re = requests.post(url=urlq, headers=headers, data=redata)
python代码再次运行,成功。
关键点:表单提交,即application/x-www-form-urlencoded 这种请求方式,
表单提交的数据,按照key1=val1&key2=val2 的方式进行编码,
key和val都进行 URL转码。
redata = urlencode(redata)