[英]urllib2.HTTPError: HTTP Error 400: Bad Request - Python
我正在嘗試使用urllib和urllib2進行開機自檢,但它一直給我這個錯誤
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()
有人可以幫我嗎?
我的心理能力建議您將body
作為json字符串發送,而不是將字典轉換為字符串。
body = '{"where" : {"deviceType" : "ios"}, "data" : {"alert" : "vvv"}}'
請注意,對json元素使用了雙引號。
我懷疑您的有效負載編碼不正確。 他們無處說“ urlencoded”。 嘗試使用自己的示例代替。 https://parse.com/docs/rest#push urrlib2是一個相當原始的庫-使用例如請求會更方便。
這取決於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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.