Sending a custom IQ query (Android)(Smack)

2019-08-01 03:42发布

问题:

Format of result will be this.

<iq from='52@localhost' to='20@localhost/Gajim' id='253' type='result'>
<query xmlns='someName'>
<item subscription='both' jid='1@localhost'/>
</query>
</iq>

I am trying to send a custom iq query with the following format.

 <iq xmlns="Name" type="get" id="253">
    <query xmlns="someName">
    <auth type='token'>asd</auth>
    </query>
    </iq>

From this I understand that I need to send a query with a authorization type token(token id ). Here is my try at that.

final IQ iq = new IQ() {  
  @Override  
  public String getChildElementXML() {  
    return "<query xmlns='someName'auth type="+t_id"+"asd<................'</query>"; // I am confused on how to write here  
  }  
};  
iq.setType(IQ.Type.get);  
connection.sendPacket(iq); // connection is an XMPPTCPConnection object.

I am confused on how to complete this getChildElementXML() and furthermore I get an error when I try to instantiate a new IQ because I need to implement some builder method. Should I create a new class for sending custom IQ queries?Can someone show how to do it?

Note: Constructive feedback is appreciated, I can make the question clearer if someone points out an ambiguity.

回答1:

This will answer your question but keep in mind in next step you'll need something like this: Mapping Openfire Custom plugin with aSmack Client


Generally speaking, ID it's created by smack API and you don't deserve to assign it manually.

Generally speaking, xmnls but to be assigned to custom tag and not IQ itself.

Our target:

 <iq from="me@domain" to="domain" type="get" id="253">
    <query xmlns="someName">
    <auth type='token'>asd</auth>
    </query>
    </iq>

How your class will look like:

package ....;

import org.jivesoftware.smack.packet.IQ;



public class IQCustomAuth extends IQ
{
public final static String childElementName = "query";
public final static String childElementNamespace = "com:prethia:query#auth";


private final String auth;
private final String typeAuth;

public IQCustomAuth(String userFrom, String server, String typeAuth, String auth)
{

    super( childElementName, childElementNamespace );
    this.setType( IQ.Type.get );
    this.auth = auth;
    this.typeAuth = typeAuth;
    setTo( server );
    setFrom( userFrom );
}



@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder( IQChildElementXmlStringBuilder xml )
{

    xml.rightAngleBracket();
    xml.halfOpenElement( "auth ");
    xml.attribute( "type", this.typeAuth );
    xml.rightAngleBracket();
    xml.append(auth);
    xml.closeElement("auth");
    return xml;
}




}

To test:

IQCustomAuth iq = new IQCustomAuth( "me@domain", "domain", "token", "asd" );
System.out.println(iq.toString());

to Send:

connection.sendPacket(new IQCustomAuth( "me@domain", "domain", "token", "asd" ));