android - 使用 Django 将推送通知发布到 C2DM (android)

标签 android django push-notification

我找到了如何使用 Django 向 Android 设备发送推送通知 here (here is the code)。

所以采用了它,我的代码如下所示:

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差不多所以我很困惑。我做错了什么?


编辑:

以防万一,这是我获取授权 token 的方式(看起来工作正常),也许我的解析有误:

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

    data  = urllib.urlencode({'accountType' : 'HOSTED_OR_GOOGLE',
                              'Email'       : 'someaccount@gmail.com',
                              '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

最佳答案

C2DM 已弃用。鼓励开发人员切换到 GCM,C2DM 将在短时间内得到支持。简单的 API,而不是不支持的 ClientLoginoAuth2

http://developer.android.com/guide/google/gcm/index.html

关于android - 使用 Django 将推送通知发布到 C2DM (android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242405/

相关文章:

java - 以编程方式调整线性布局的高度

android - 将 TabHost 中的一个 fragment 替换为另一个 fragment

python - Celery重启丢失定时任务

ios - Azure 通知中心与 APNS

android - 在 OneSignal 中分割用户

通过服务的 Android 通知

Android:将对象从一个 Activity 发送到另一 Activity

android - 使用 PhoneGap 的 FileTransfer 传递 cookie

python - 在许多单独的线程中测试 Django 应用程序

python - Django 中的原始 SQL 查询