urllib2.HTTPError:HTTP错误400:错误请求 - Python

时间:2015-02-06 22:09:32

标签: python urllib2 urllib

我尝试使用urllib和urllib2进行POST但是它一直给我这个错误

    Traceback (most recent call last):
  File "/Users/BaDRaN/Desktop/untitled text.py", line 39, in <module>
    response = urllib2.urlopen(request)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

这是我的代码

body    = {'where' : {'deviceType' : 'ios'}, 'data' : {'alert' : 'vvv'}}
headers = { 'X-Parse-Application-Id' : 'someID', 'X-Parse-REST-API-Key' : 'someKey', 'Content-Type' : 'application/json' }

data     = urllib.urlencode(body)
request  = urllib2.Request('https://api.parse.com/1/push', data, headers)
response = urllib2.urlopen(request)
call     = response.read()

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

我的通灵能力建议您要将body作为一串json发送,而不是将其转换为字符串。

body = '{"where" : {"deviceType" : "ios"}, "data" : {"alert" : "vvv"}}'

注意json元素使用双引号。

答案 1 :(得分:0)

我怀疑您的有效负载未正确编码。他们没有说“urlencoded”。请尝试使用他们自己的示例。 https://parse.com/docs/rest#push urrlib2是一个相当原始的库 - 使用例如请求会更方便。

答案 2 :(得分:0)

这取决于json数据是否格式正确,或者问题出在标题内容中。因此urllib2.HTTPError: HTTP Error 400: Bad Request通常会发生。

下面的一小段代码,带有带有标头的basic64认证和用于PUT / POST方法的json数据:

import urllib2
import base64
import json
url = 'Your_URL'
auth = 'Basic ' + base64.encodestring('%s:%s' % ('username','password'))[:-1]
content_header = {'Authorization': auth,
                 'Content-Type':'application/json',
                 'Accept':'application/json'}
json_data = YOUR_DATA
request = urllib2.Request(url=url, data=json.dumps(json_data), headers=content_header)
request.get_method = lambda: 'PUT' #If you will not provide this, then it will be POST
response = urllib2.urlopen(request)