向UrbanAirship发送POST请求时发出HTTP 400响应

时间:2011-10-09 15:30:07

标签: python http post web2py

我正在使用Web2Py创建一个简单的应用程序,通过UrbanAirship发送推送通知。出于某种原因,当我尝试通过我的代码发送它时,我得到了400响应。它使用REST客户端可以正常运行UA API。这是我的代码:

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

据我所知,问题在于发送数据的格式。我哪里错了?

1 个答案:

答案 0 :(得分:0)

urllib.urlencode函数用于创建URL编码的参数体(Content-Type: application/x-www-form-urlencoded)。对于显然你想要的JSON,请改用json.dumps

相关问题