Smack 4.1与gtalk的连接

时间:2015-04-08 14:53:59

标签: smack

我更新了1.4,但现在无法连接到gtalk。这是我正在使用的代码:

XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
    configBuilder.setHost("talk.google.com");       
    configBuilder.setPort(5222);
    configBuilder.setServiceName("gmail.com");
    configBuilder.setSecurityMode(SecurityMode.required);
    configBuilder.setDebuggerEnabled(true);
    configBuilder.setSendPresence(true);  
    configBuilder.setUsernameAndPassword(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));

    SASLAuthentication.blacklistSASLMechanism(SASLMechanism.PLAIN);
    AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
    try
    {
        connection.connect();
        connection.login();//.login(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));
    }
    catch(Exception e)
    {
        e.printStackTrace();
        return null;
    }

这是我得到的错误:

D/SMACK(12807): SENT (3): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-OAUTH2'>REMOVED_THIS=</auth>
D/SMACK(12807): RECV (3): <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><incorrect-encoding/></failure>

1 个答案:

答案 0 :(得分:4)

问题在于SASLXOauth2Mechanism:

Base64.encode(toBytes('\u0000' + authenticationId + '\u0000' + password));

作为代码中的快速测试替换

AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());

用这个

    AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build())
    {
        @Override
        public void send(PlainStreamElement auth) throws NotConnectedException
        {
            if(auth instanceof AuthMechanism)
            {           
                final XmlStringBuilder xml = new XmlStringBuilder();
                xml.halfOpenElement(AuthMechanism.ELEMENT)
                .xmlnsAttribute(SaslStreamElements.NAMESPACE)
                .attribute("mechanism", "X-OAUTH2")
                .attribute("auth:service", "oauth2")
                .attribute("xmlns:auth", "http://www.google.com/talk/protocol/auth")
                .rightAngleBracket()
                .optAppend(Base64.encodeToString(StringUtils.toBytes("\0" + authenticationId + "\0" + password)))
                .closeElement(AuthMechanism.ELEMENT);                   
                 super.send(new PlainStreamElement()
                 {
                    @Override
                    public String toXML()
                    {
                        return xml.toString();
                    }                        
                 });                 
            }   
            else super.send(auth);
        }
    };

我没有测试它,但我希望它有效。 authenticationId和token是您的凭据。