How to send custom XML data using the Smack library?

BinRoot picture BinRoot · Jun 17, 2011 · Viewed 14.7k times · Source

I'm using the Smack API in Java to connect to my XMPP server.

I want to send a customized message packet like this:

<message to="[email protected]" type="chat" MYFIELD="custom stuff">
    <body> hi </body>
    <CUSTOM_STANZA A="..." B="..."> 
        C="..." 
        D="..."
    </CUSTOM_STANZA>
</message>

I'm guessing that I create implement my own Packet with that returns this XML in it's toXML() method. But that doesn't seem to work.

Any help would be appreciated.

Answer

Robin picture Robin · Jun 17, 2011

i don't know why you want to add custom attributes to the message. This will be problematic on the client and may cause issues on the server as well since it will not match the schema for the message stanza.

The message content, on the other hand is easily handled as @Femi said with a packet extension. You need to create a MyExtension which extends PacketExtension, and the toXML() in that class will return your custom stanza.

You can create and send your custom message by:

Message message = new Message();
message.addExtension(new MyExtension());
chat.sendMessage(message);

To read the stanza, you will want to register a provider, which will create and return your custom PacketExtension. You should take a look at the EmbeddedExtensionProvider for this as it handles the tag parsing for you, thus simplifying the process.