开发者

HTTP 400 response while sending POST request to UrbanAirship

I am using Web2Py to create a simple app which sends Push notifications through UrbanAirship. For some reason, I am getting a 400 response when I try to send it through my code. It UA API works fine using REST client. This is my code:

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

As far as I can understand, the problem is in the format o开发者_开发知识库f data being sent. Where am I going wrong?


The urllib.urlencode function is for making a URL-encoded parameter body (Content-Type: application/x-www-form-urlencoded). For JSON, which is apparently what you want, use json.dumps instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜