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

0 投票
1 回答
1256 浏览
提问于 2025-04-17 03:59

我正在使用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

urllib.urlencode这个函数是用来生成一种特定格式的参数,叫做URL编码的参数体(也就是Content-Type: application/x-www-form-urlencoded)。不过,如果你想用JSON格式的数据,建议你使用json.dumps这个函数。

撰写回答