如何使用纯 python 2.6 发送 GCM 通知

How to send GCM notification using pure python 2.6

我正在尝试编写一个简单的脚本来检查 GCM registration_ids 换句话说,尝试重新创建 cURL 请求

curl -i -X POST \
   -H "Authorization:key=auth_key" \
   -H "Content-Type:application/json" \
   -d '{"registration_ids": ["reg_key"], "data": {"test": "test"}}' \
 'https://android.googleapis.com/gcm/send'

python

这是我的代码

conn = httplib.HTTPSConnection("android.googleapis.com")
conn.connect()
conn.set_debuglevel(1)

body = {}
body['data'] =  {'test': 'test', 'dry-run' : True}
body['registration_ids'] = [key]
print "Send data \n" + str(body)
conn.putrequest('POST', '/gcm/send', str(body))
conn.putheader('Authorization', 'key='+auth_key)
conn.putheader('Content-Type','application/json')
conn.putheader('Content-Length', "%d" % len(str(body)))
conn.endheaders()
response = conn.getresponse()

出于某种原因,尽管我的 cURL 工作正常,但当我使用 python 时,我从服务器得到了这样的响应

send: 'POST /gcm/send HTTP/1.1\r\nAccept-Encoding: identity\r\nAuthorization: key=auth_key\r\nContent-Type: application/json\r\nContent-Length: 252\r\n\r\n'
reply: 'HTTP/1.1 404 Not Found\r\n'
header: Content-Type: text/html; charset=UTF-8
header: Content-Length: 1433
header: Date: Thu, 12 Feb 2015 17:07:54 GMT
header: Server: GFE/2.0
header: Connection: close

所以请帮我找出我做错了什么,在此先感谢。

PS 如果我在 python 脚本中省略 Content-Length header,我将得到 411 内容长度必需,尽管 cURL 不包含此 header。对我来说又是一个谜。

您的 content-type 是 json,但是您发送的数据只是一个字符串,您可能需要使用 json.dump() 方法来转换您的字典。

您可能想查看此 post 中的答案:Python JSON POST request

谢谢大家的回答,我就这样结束了

    body = {}
    body['data'] =  {'test': 'test', 'dry-run' : True}
    body['registration_ids'] = [key]
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain', 'Authorization':'key='+auth_key}
    print "Send data \n" + str(body)
    conn.request('POST', '/gcm/send', json.dumps(body), headers)
    response = conn.getresponse()

我不知道为什么这行得通,而我问题中的代码却行不通,有人可以解释一下吗?

PS 只做 json.dumps(body) 并不能解决问题。