Python中的POST请求返回urllib2.HTTPError:HTTP错误400:Bad Reques

2024-05-29 07:43:09 发布

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

我正在尝试使用Zendesk的核心API创建新的组织。我已经可以打其他电话没有问题,但这一个继续失败。以下代码演示了该问题:

url = "https://mydomain.zendesk.com/api/v2/organizations.json"
new_org = {"organization": {"name": "new organization"}}
data = urllib.urlencode(new_org)
req = urllib2.Request(url,data)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, 'me@email.com', 'fakepassword')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
response = urllib2.urlopen(req)
bla = response.read()

出现以下错误:

^{pr2}$

任何帮助将不胜感激!谢谢。在


Tags: orgcomauthurl核心newdataresponse
1条回答
网友
1楼 · 发布于 2024-05-29 07:43:09

您的问题与urllib.urlencode的使用有关。因为the documentation表示这将:

Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string.

Zendesk Organizations API期望接收JSON数据作为请求的主体。Zendesk无法理解您的请求,因为它的格式错误。返回的400状态代码表明了这一点。状态代码上的Wikipedia Page将400状态代码描述为:

The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

现在,您可以通过如下方式在请求中正确包含数据来解决此问题:

req = urllib2.Request(url, json.dumps(new_org))

如果使用requests库,您将真正为自己节省大量的精力。我无法访问Zendesk进行测试,但我怀疑您的代码可能会被重写为:

^{pr2}$

相关问题 更多 >

    热门问题