我试图编写一个简单的脚本来检查 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标头,我将获得411内容长度,尽管cURL不包含此标头。对我来说是另一个谜。
答案 0 :(得分:1)
您的content-type
是json,但您发送的数据只是一个字符串,您可能希望使用json.dump()
方法转换字典。
您可能希望查看此帖子中的答案:Python JSON POST request
答案 1 :(得分:0)
感谢大家的回答,我最终得到了这个
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)
并没有解决问题。