Python Post 调用抛出 400 Bad Request

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32659134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:59:22  来源:igfitidea点击:

Python Post call throwing 400 Bad Request

pythonrestcurl

提问by RIPAN

I am writing a python script which will call a REST POST endpoint but in response I am getting 400 Bad Request where as if I do same request with curl, it returns me 200 OK. Code snippet for python script is below

我正在编写一个 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()

and corresponding curl request is

和相应的卷曲请求是

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/

Now I am not able figure out where is the issue in python script.

现在我无法弄清楚python脚本中的问题在哪里。

采纳答案by Du?an Ma?ar

Try using requests(install with pip install requests) instead of urllib.

尝试使用requests(install with pip install requests) 而不是urllib.

Also, enclose your data as JSONin the request body, don't pass them as URL parameters. You are passing JSONdata in your curlexample as well.

此外,将您的数据包含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

EDIT

编辑

From https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests:

来自https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests

Note, the jsonparameter is ignored if either dataor filesis passed.

Using the jsonparameter in the request will change the Content-Typein the header to application/json.

请注意,json如果传递了data或,则忽略该参数files

使用json请求中的参数会将Content-Type标头中的更改为application/json

回答by Renjith Thankachan

The problem in your code is, you set Content-Typeheader as application/jsonand not sending data in json format

您的代码中的问题是,您将Content-Type标头设置为application/jsonjson 格式而不是发送数据

 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()