意外的令牌在Python POST请求的位置0处的文件结尾处的Firebase

问题描述:

我试图通过Firebase向某个客户端发送消息。这是我目前(测试)代码:意外的令牌在Python POST请求的位置0处的文件结尾处的Firebase

import json 
import requests 
import urllib 

def send_message(): 
    server = "https://fcm.googleapis.com/fcm/send" 
    api_key = "xxx" 
    user_token = "xxx" 

    headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key} 

    data = {"type": "dataUpdate"} 
    payload = {"data": data, "to": user_token} 
    payload = json.dumps(payload) 

    res = requests.post(server, headers=headers, json=payload) 

    return res 

产生以下错误,由火力地堡返回:

JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0. 

以下JSON发送到火力地堡似乎是正确的对我说:

{ 
    "data": { 
     "type":"dataUpdate" 
    }, 
    "to":"xxx" 
} 

,其格式为Firebase documentation。任何想法为什么Firebase不接受给定的数据?

当您使用json=payload作为requests.post()的参数时,您不需要在标头中指定'Content-Type': 'application/json'。此外,要传递一个字符串时的参数应该是​​作为一个字典(即无需json.dumps()

试试这个:

def send_message(): 
    server = "https://fcm.googleapis.com/fcm/send" 
    api_key = "xxx" 
    user_token = "xxx" 

    headers = {'Authorization': 'key=' + api_key} 

    data = {"type": "dataUpdate"} 
    payload = {"data": data, "to": user_token} 

    res = requests.post(server, headers=headers, json=payload) 

    return res 
+0

这种方法的工作原理。非常感谢你。 – CPUFry

+0

@ OpenUserX03为什么设置content-type:application/json头会导致请求失败?我很担心,因为这样的事情可能会错误地发生。 –

+0

@PubuduDodangoda它不应该,只要指定'json'参数就没有必要 – OpenUserX03