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

Python 向UrbanAirship发送POST请求时HTTP 400响应,python,http,post,web2py,Python,Http,Post,Web2py,我正在使用Web2Py创建一个简单的应用程序,通过UrbanAirship发送推送通知。由于某种原因,当我尝试通过代码发送时,我得到了400响应。使用REST客户端,它可以很好地工作。这是我的代码: url = 'https://go.urbanairship.com/api/push/' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_pass

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

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
url='1〕https://go.urbanairship.com/api/push/'
passman=urllib2.HTTPPasswordMgrWithDefaultRealm()
#这将创建一个密码管理器
密码(无、url、用户名、密码)
#因为我们一开始没有放任何东西,所以它将永远
#对URL使用此用户名/密码组合
#其中'theurl'是一个超级url
authhandler=urllib2.HTTPBasicAuthHandler(passman)
#创建AuthHandler
opener=urlib2.build\u opener(authhandler)
urllib2.install_opener(opener)
#所有对urllib2.urlopen的调用现在都将使用我们的处理程序
#确保不将协议包含在URL中,或
#HTTPPasswordMgrWithDefaultRealm将非常混乱。
#不过,在获取页面时,您(当然)必须使用它。
值={“设备令牌”:[“”],“aps”:{“警报”:“你好!”}
data=urllib.urlencode(值)
headers={'Content-Type':'application/json'}
请求(url、数据、标题)
尝试:
响应=urllib2.urlopen(请求)
返回响应
除IOError外,e:
如果e.code==200:
返回“推送发送!”
其他:
return“服务器无法完成请求。”。错误:%d“%e”代码

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

函数用于生成URL编码的参数体(
内容类型:application/x-www-form-urlencoded
)。对于JSON,这显然是您想要的,请改用