2011-10-09 117 views
0

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

據我可以理解,問題是數據的格式發送。我哪裏錯了?

回答

0

urllib.urlencode函數用於製作URL編碼參數體(Content-Type: application/x-www-form-urlencoded)。對於顯然是您想要的JSON,請改用json.dumps

+0

我完全錯過了這一點,謝謝! – Mus