无法使用Django在GCM中发送POST请求

Nul*_*ify 5 python django python-requests google-cloud-messaging

这是我的看法:

@csrf_exempt
def send_notification(request):
    message = {"name": "xxxxx","email": "xxxxxx@gmail.com"}
    registration_ids = ['xxxxxxxxxxxxxx']
    post_data = {"data":message,"registration_ids":registration_ids}
    headers = {'Content-Type': 'application/json', 'Authorization':'key=xxxxxx'}
    import requests
    post_response = requests.post(url='https://android.googleapis.com/gcm/send', data=simplejson.dumps(post_data), headers=headers)  
    print post_response
    print simplejson.dumps([post_response.headers, post_response.text])

    to_json = {'status':str(post_response)}
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Run Code Online (Sandbox Code Playgroud)

服务器日志:

[error] <Response [401]>
Run Code Online (Sandbox Code Playgroud)

输出:

TypeError at /send_notification/

CaseInsensitiveDict(
    {
        "alternate-protocol": "443:quic",
        "x-xss-protection": "1; mode=block",
        "x-content-type-options": "nosniff",
        "transfer-encoding": "chunked",
        "expires": "Fri, 08 Nov 2013 10:29:45 GMT",
        "server": "GSE",
        "cache-control": "private, max-age=0",
        "date": "Fri, 08 Nov 2013 10:29:45 GMT",
        "x-frame-options": "SAMEORIGIN",
        "content-type": "text/html; charset=UTF-8"
   }) is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我正在使用requests它给了我上面这一行.

我也试过测试其他工作的网址!

怎么可能出错?

Mar*_*ers 2

如果您收到来自 Google 的 401 响应,则授权失败。记录的授权故障排除页面指出了此类失败的以下原因:

  • 授权标头丢失或语法无效。
  • 作为密钥发送的项目编号无效。
  • 密钥有效,但 GCM 服务已禁用。
  • 请求源自未列入服务器密钥 IP 白名单的服务器。

确保您的密钥有效、已启用,并且您的 IP 地址已正确列入白名单。IP 地址是 Django 服务器联系 API 时 Google 服务看到的地址。