我正在编写一个python脚本,该脚本将调用REST POST端点,但作为响应,我收到400个错误请求,其中,如果我对curl执行相同的请求,它将返回200 OK。下面是python脚本的代码片段
import httplib,urllib
def printText(txt):
lines = txt.split('\n')
for line in lines:
print line.strip()
httpServ = httplib.HTTPConnection("127.0.0.1", 9100)
httpServ.connect()
params = urllib.urlencode({"externalId": "801411","name": "RD Core","description": "Tenant create","subscriptionType": "MINIMAL","features": {"capture":False,"correspondence": True,"vault": False}})
headers = {"Content-type": "application/json"}
httpServ.request("POST", "/tenants", params, headers)
response = httpServ.getresponse()
print response.status, response.reason
httpServ.close()
相应的curl请求是
curl -iX POST \
-H 'Content-Type: application/json' \
-d '
{
"externalId": "801411",
"name": "RD Core seed data test",
"description": "Tenant for Core team seed data testing",
"subscriptionType": "MINIMAL",
"features": {
"capture": false,
"correspondence": true,
"vault": false
}
}' http://localhost:9100/tenants/
现在我不知道python脚本中的问题在哪里。
尝试使用
requests
(使用pip install requests
安装)而不是urllib
。另外,将数据作为
JSON
封装在请求正文中,不要将它们作为URL参数传递。您也在JSON
示例中传递curl
数据。编辑
来自https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests:
代码中的问题是,将
Content-Type
头设置为application/json
,并且不以json格式发送数据相关问题 更多 >
编程相关推荐