我正在编写一个python脚本,它将调用一个REST POST端点,但作为响应,我收到400 Bad Request,好像我用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脚本中的问题在哪里。
答案 0 :(得分:16)
尝试使用requests
(使用pip install requests
安装)代替urllib
。
另外,请将您的数据JSON
括在请求正文中,不要将其作为网址参数传递。您也在JSON
示例中传递了curl
个数据。
import requests
data = {
"externalId": "801411",
"name": "RD Core",
"description": "Tenant create",
"subscriptionType": "MINIMAL",
"features": {
"capture": False,
"correspondence": True,
"vault": False
}
}
response = requests.post(
url="http://localhost:9100/tenants/",
json=data
)
print response.status_code, response.reason
修改强>
来自https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests:
注意,如果传递了
json
或data
,则会忽略files
参数。在请求中使用
json
参数将更改Content-Type
在application/json
的标题中。
答案 1 :(得分:0)
您的代码中的问题是,您将Content-Type
标头设置为application/json
而不是以json格式发送数据
import httplib, json
httpServ = httplib.HTTPConnection("127.0.0.1", 9100)
httpServ.connect()
headers = {"Content-type": "application/json"}
data = json.dumps({
"externalId": "801411",
"name": "RD Core",
"description": "Tenant create",
"subscriptionType": "MINIMAL",
"features": {
"capture": False,
"correspondence": True,
"vault": False
}
})
# here raw data is in json format
httpServ.request("POST", "/tenants", data, headers)
response = httpServ.getresponse()
print response.status, response.reason
httpServ.close()