Python调用后抛出400个错误请求

2024-09-29 23:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: coretxt脚本forresponselineparamsurllib
2条回答

尝试使用requests(使用pip install requests安装)而不是urllib

另外,将数据作为JSON封装在请求正文中,不要将它们作为URL参数传递。您也在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

Note, the json parameter is ignored if either data or files is passed.

Using the json parameter in the request will change the Content-Type in the header to application/json.

代码中的问题是,将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()

相关问题 更多 >

    热门问题