Python Post调用400 Bad Request

时间:2015-09-18 18:53:15

标签: python rest curl

我正在编写一个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脚本中的问题在哪里。

2 个答案:

答案 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

  

注意,如果传递了jsondata,则会忽略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()