GCM Invalid JSON Missing Payload

ぃ、小莉子 提交于 2019-12-13 03:38:25

问题


I am trying to send messages through Google Cloud Messaging, using Python sleekXMPP. I tried to follow the sample in the GCM docs. However, I am getting an "InvalidJson : MissingPayload" error response (400) when I call send_command. What am I missing here? The following is the code that I use.

def random_id():
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))

class GcmNotifier(sleekxmpp.ClientXMPP):

    def __init__(self, jid, password):
        super(GcmNotifier, self).__init__(jid, password)
        self.add_event_handler('message', self.on_message_received)

    def send_gcm_message(self, message):
        body = '<gcm xmlns:"google:mobile:data">%s</gcm>' % json.dumps(message)
        print(body)
        self.send_message(mto='', mbody=body)

    def on_message_received(self, message):
        print(message)

    def send_command(self, recipient):
        self.send_gcm_message({ 
            'to': recipient,
            'message_id': random_id(),
            'data':
            {
                'hello': 'world'
            }
        })

xmpp = GcmNotifier(GCM_SENDER_ID + '@gcm.googleapis.com', GCM_API_KEY)
if xmpp.connect((GCM_SERVER, GCM_PORT), use_ssl=True):
    xmpp.process(block=False)

This is the error that I receive:

<message to="REDACTED@gcm.googleapis.com/475DBA7C" type="error" xml:lang="en"><body>&lt;gcm xmlns:&quot;google:mobile:data&quot;&gt;{&quot;to&quot;: &quot;REDACTED&quot;, &quot;data&quot;: {&quot;hello&quot;: &quot;world&quot;}, &quot;message_id&quot;: &quot;ZGDZ9QTD&quot;}&lt;/gcm&gt;</body><error code="400" type="modify"><bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" /><text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">InvalidJson : MissingPayload</text></error></message>


回答1:


The error you are receiving for Missing Payload is because you are not passing any parameter as Key and value format to be recognized as payload.

First you have to define a function where you are going to pass the payload and then covert it back to the plain text after the GCm server responds back.

Here is an example:

def plaintext_request(self, registration_id, data=None, collapse_key=None,
                          delay_while_idle=False, time_to_live=None, retries=5, dry_run=False):
if not registration_id:
        raise GCMMissingRegistrationException("Missing registration_id")

    payload = self.construct_payload(
        registration_id, data, collapse_key,
        delay_while_idle, time_to_live, False, dry_run
    )

You can have the exponential Back-Off mechanism if you need to have in your code that would ping the server after some duration.

For the detail code implementation, please read the following document.




回答2:


It turns out SleekXMPP was automatically enclosing my message in <body /> tags, which is not the expected message format by the GCM server. I ended up solving the problem by defining my own stanzas, like this:

 class Gcm(ElementBase):
    namespace = 'google:mobile:data'
    name = 'gcm'
    plugin_attrib = 'gcm'
    interfaces = set('gcm')
    sub_interfaces = interfaces

class GcmMessage(ElementBase):
    namespace = ''
    name = 'message'
    interfaces = set('gcm')
    sub_interfaces = interfaces
    subitem = (Gcm,)

register_stanza_plugin(GcmMessage, Gcm)

and then by sending the message like this:

def send_gcm_message(self, message):
    msg = GcmMessage()
    msg['gcm'].xml.text = xml.sax.saxutils.escape(json.dumps(message, ensure_ascii=False))
    self.send(msg)


来源:https://stackoverflow.com/questions/30393534/gcm-invalid-json-missing-payload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!