【问题标题】:Not able to send a POST request in GCM using Django无法使用 Django 在 GCM 中发送 POST 请求
【发布时间】:2013-11-20 07:11:12
【问题描述】:

这是我的看法:

@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')

服务器日志:

[error] <Response [401]>

输出:

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

我正在使用requests,这给了我上面的行。

我还尝试测试其他一些有效的网址!

可能出了什么问题?

【问题讨论】:

  • 正确,因此 API 会为您提供 401 错误响应。查看该响应的标题和正文以获取线索。 dumps([post_response.headers, post_response.text]) 说什么?
  • 另外,您阅读文档中的401 error troubleshooting section了吗?
  • 对,但这至少告诉我们标题不包含错误反馈。删除标题,只返回post_response.text
  • @KousikChowdhury: np;所以故障排除页面是正确的:请求来自未在服务器密钥 IP 中列入白名单的服务器
  • @KousikChowdhury:我已经将其发布为答案,供未来访问该问题的人使用。

标签: python django google-cloud-messaging python-requests


【解决方案1】:

如果您收到来自 Google 的 401 响应,则说明授权失败。 documented authorization troubleshooting page 说明了此类失败的以下原因:

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

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

【讨论】:

  • 我遇到了另一个问题。我收到来自 GCM 的设备中的 null 响应。我在多个设备中正确收到通知。但是消息以 null 形式出现。在我的 GCM 应用程序 API 项目流量报告中,我收到 Total requests 0 | Requests/day 0 peak | 0.00 average 它与我的消息语法有关吗?我已经打开了另一个问题@stackoverflow.com/questions/19901981/…
猜你喜欢
  • 2016-10-16
  • 2020-12-29
  • 1970-01-01
  • 2022-01-15
  • 2013-03-08
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多