发送POST请求到UrbanAirship时的HTTP 400响应
问题描述:
我正在使用Web2Py创建一个简单的应用程序,通过UrbanAhiphip发送Push通知。出于某种原因,当我尝试通过我的代码发送时,我收到了400条回应。它使用REST客户端的UA API工作正常。这是我的代码:发送POST请求到UrbanAirship时的HTTP 400响应
url = 'https://go.urbanairship.com/api/push/'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, url, username, password)
# because we have put None at the start it will always
# use this username/password combination for urls
# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.
values = {"device_tokens": ["<DEVICE TOKEN>"], "aps": {"alert": "Hello!"}}
data = urllib.urlencode(values)
headers = {'Content-Type': 'application/json'}
req = urllib2.Request(url, data, headers)
try:
response = urllib2.urlopen(req)
return response
except IOError, e:
if e.code == 200:
return "Push sent!"
else:
return 'The server couldn\'t fulfill the request. Error: %d' % e.code
据我可以理解,问题是数据的格式发送。我哪里错了?
答
urllib.urlencode
函数用于制作URL编码参数体(Content-Type: application/x-www-form-urlencoded
)。对于显然是您想要的JSON,请改用json.dumps
。
我完全错过了这一点,谢谢! – Mus