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

时间:2014-03-19 15:03:31

标签: python zendesk

我正在尝试使用他们的Core API在Zendesk中创建新的组织。我已经能够毫无问题地拨打其他电话,但这一次仍然失败。以下代码演示了此问题:

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

发生以下错误:

  Traceback (most recent call last):
  File "/network/nfshome0/homestore00/me/workspace/Pythony/pythony/test2.py", line   35, in <module>
    response = urllib2.urlopen(req)
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 406, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 438, in error
    result = self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 890, in http_error_401
    url, req, headers)
  File "/usr/lib/python2.7/urllib2.py", line 865, in http_error_auth_reqed
    response = self.retry_http_basic_auth(host, req, realm)
  File "/usr/lib/python2.7/urllib2.py", line 878, in retry_http_basic_auth
    return self.parent.open(req, timeout=req.timeout)
  File "/usr/lib/python2.7/urllib2.py", line 406, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 444, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

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

1 个答案:

答案 0 :(得分:0)

您的问题与urllib.urlencode的使用有关。由于the documentation表示会:

  

将映射对象或两元素元组序列转换为“百分比编码”字符串。

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

  

由于被认为是客户端错误的内容(例如,格式错误的请求语法,无效的请求消息框架或欺骗性请求路由),服务器无法或不会处理请求。

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

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

如果您使用requests库,那么您真的可以节省很多精力。我没有访问Zendesk来测试这个,但我怀疑你的代码可以改写为:

import requests

new_org = {"organization": {"name": "new organization"}}
response = requests.post(
    "https://mydomain.zendesk.com/api/v2/organizations.json",
    auth=('me@email.com', 'fakepassword'),
    data=new_org
)
data = response.json()