gpt4 book ai didi

python - 谷歌云消息 HTTP 错误 400 : Bad Request

转载 作者:太空狗 更新时间:2023-10-29 18:29:51 26 4
gpt4 key购买 nike

我正在尝试通过 GCM(Google 云消息传递)发送消息。我已经通过 Google API 注册,我可以从多个 Android 测试手机向我的网站(这是一个 Google App Engine 后端)发送一个 regID。但是,我无法从 Google App Engine 向 GCM 发送任何内容。这是我正在尝试使用的内容。

    regId = "APA91b..."

json_data = {"collapse_key" : "Food-Promo", "data" : {
"Category" : "FOOD",
"Type": "VEG",
}, "registration_ids": [regId],
}


url = 'https://android.googleapis.com/gcm/send'




apiKey = "AI..."
myKey = "key=" + apiKey

headers = {'Content-Type': 'application/json', 'Authorization': myKey}
data = urllib.urlencode(json_data)
data2 = {"title": title}
data3 = urllib.urlencode(data2)

req = urllib2.Request(url, data, headers)


f = urllib2.urlopen(req)
response = f.read()
f.close()

logging.debug("***!!!!!!!WriteEntry TEST ----- Response: " + response)

这是我收到的错误。

Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 703, in __call__
handler.post(*groups)
File "/base/data/home/apps/s~journaltestza/26.360625174851783344/main.py", line 213, in post
f = urllib2.urlopen(req)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 124, in urlopen
return _opener.open(url, data)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 387, in open
response = meth(req, response)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 425, in error
return self._call_chain(*args)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request

谢谢!

最佳答案

data2 和 data3 有什么用?您发布的数据不是正确的 json,因此您需要使用 json.dumps(data)。代码应该是这样的:

json_data = {"collapse_key" : "Food-Promo", "data" : {
"Category" : "FOOD",
"Type": "VEG",
}, "registration_ids": [regId],
}


url = 'https://android.googleapis.com/gcm/send'
apiKey = "AI..."
myKey = "key=" + apiKey
data = json.dumps(json_data)
headers = {'Content-Type': 'application/json', 'Authorization': myKey}
req = urllib2.Request(url, data, headers)
f = urllib2.urlopen(req)
response = json.loads(f.read())
reply = {}
if response ['failure'] == 0:
reply['error'] = '0'
else:
response ['error'] = '1'
return HttpResponse(json.dumps(reply), mimetype="application/javascript")

关于python - 谷歌云消息 HTTP 错误 400 : Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11697096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com