2012-06-28 157 views
1

我發現如何使用Django herehere is the code)向Android設備發送推送通知。使用Django推送通知到C2DM(android)

所以採用了和我的代碼如下所示:

def sendAndroidPushNotification(registration_id, collapse_key, a, b) : 
    try: 
     auth = getNewAndroidAuthorizationToken() # this works I'm fetching new token so this is up to date (its length is 267 characters) 
     push_request = urllib2.Request("https://android.apis.google.com/c2dm/send") 

     data = urllib.urlencode({'data.testA'  : a, 
           'data.testB'  : b, 
           'collapse_key' : collapse_key, 
           'registration_id': registration_id 
           }) 
     push_request.add_data(data) 
     push_request.add_header('Authorization', 'GoogleLogin auth=' + auth) 
     push_request.add_header('Content-Type', 'application/x-www-form-urlencoded') 
     push_request.add_header('Content-Length', len(data)) 
     urllib2.build_opener().open(push_request) 

    except urllib2.HTTPError as e: 
     print 'got exception during push notification' 
     print 'Reason: "{0}" code: {1}'.format(e.reason, e.code) 

     pass 

這給我的錯誤:「原因:‘未授權’代碼:401」(在某些時候是403)。版本使用httplib.HTTPSConnection而不是urllib2.Request也有同樣的問題。

它看起來幾乎與code shown here一樣,所以我完全困惑。我做錯了什麼?


編輯:

以防萬一,這裏是我如何獲取授權令牌(它看起來像它正常工作),也許我的分析是錯誤的:

def getNewAndroidAuthorizationToken() : 
    request = urllib2.Request("https://www.google.com/accounts/ClientLogin") 

    data = urllib.urlencode({'accountType' : 'HOSTED_OR_GOOGLE', 
           'Email'  : '[email protected]', 
           'Passwd'  : 'asdjsdfa', 
           'service'  : 'ac2dm', 
           'source'  : 'com.mycompany.mypackage',}) 
    request.add_data(data) 

    content = urllib2.build_opener().open(request) 

    lines = content.readlines() 
    for line in lines : 
     if line.find("Auth=")==0 : 
      return line[5:] 
    return 

回答