我正在尝试编写一个简单的脚本,该脚本应检查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标头,尽管cURL不包含此标头,但我将获得411 Content Length要求。我的另一个谜。
最佳答案
您的content-type
是json,但是您要发送的数据只是一个字符串,您可能希望使用json.dump()
方法来转换字典。
您可能想查看这篇文章中的答案:Python JSON POST request
关于python - 如何使用纯Python 2.6发送GCM通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28483870/