我如何在Android中使用aSmack XMPP库实现facebook聊天(2014)?

我如何在Android中使用aSmack XMPP库实现facebook聊天(2014)?,facebook,facebook-graph-api,chat,Facebook,Facebook Graph Api,Chat,我搜索了很多地方,想找到将facebook聊天系统集成到Android/中的方法,但没有一个完全奏效。有人能提供一个与最新版本的API一起使用的工作示例吗?使用X-FACEBOOK-PLATFORMsaslauthentification进行身份验证。2014年1月14日通过Android 4.2.2验证工作 jabber ID不是username@chat.facebook.com. 它被解析为一个数字id,您可以对照花名册进行检查 ChatActivity.java public void

我搜索了很多地方,想找到将facebook聊天系统集成到Android/中的方法,但没有一个完全奏效。有人能提供一个与最新版本的API一起使用的工作示例吗?

使用X-FACEBOOK-PLATFORMsaslauthentification进行身份验证。2014年1月14日通过Android 4.2.2验证工作

jabber ID不是username@chat.facebook.com. 它被解析为一个数字id,您可以对照花名册进行检查


ChatActivity.java

public void connectToFb() throws XMPPException {        
        ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
        SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
        SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
        config.setSASLAuthenticationEnabled(true);
        config.setSecurityMode(SecurityMode.required);
        config.setSendPresence(false);
        XMPPConnection xmpp = new XMPPConnection(config);
        try {
            xmpp.connect();
            xmpp.login(Session.getActiveSession().getApplicationId(), Session.getActiveSession().getAccessToken(), "Application");

            //send a chat message           
            ChatManager chatmanager = xmpp.getChatManager();
            Chat newChat = chatmanager.createChat("<jabber-id-here>@chat.facebook.com", new MessageListener() {
                @Override
                public void processMessage(Chat chat, Message msg) {
                    Log.d("test", "message sent = "+ msg);
                }
            });
            newChat.sendMessage("Cowdy!");    

            //get roster  
            Roster roster = xmpp.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
            System.out.println("Connected!");
            System.out.println("\n\n" + entries.size() + " buddy(ies):");
            for (RosterEntry entry : entries) {
                Log.i("test", entry.getName());
                Log.i("test", entry.getUser());
            }
        } catch (XMPPException e) {
            xmpp.disconnect();
            e.printStackTrace();
        }
    }
public class SASLXFacebookPlatformMechanism extends SASLMechanism {

        public static final String NAME = "X-FACEBOOK-PLATFORM";
        private String apiKey = "";
        private String accessToken = "";


        /**
         * Constructor.
         */
        public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication) {
            super(saslAuthentication);
        }

        @Override
        protected void authenticate() throws IOException, XMPPException {
            // Send the authentication to the server
            getSASLAuthentication().send(new AuthMechanism(getName(), ""));
        }

        @Override
        public void authenticate(String apiKey, String host, String accessToken) throws IOException, XMPPException {
            this.apiKey = apiKey;
            this.accessToken = accessToken;
            this.hostname = host;

            String[] mechanisms = { "DIGEST-MD5" };
            Map<String, String> props = new HashMap<String, String>();
            this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
            authenticate();
        }

        @Override
        protected String getName() {
            return NAME;
        }

        @Override
        public void challengeReceived(String challenge) throws IOException {
            byte[] response = null;

            if (challenge != null) {
                String decodedChallenge = new String(Base64.decode(challenge));
                Map<String, String> parameters = getQueryMap(decodedChallenge);

                String version = "1.0";
                String nonce = parameters.get("nonce");
                String method = parameters.get("method");

                long callId = new GregorianCalendar().getTimeInMillis() / 1000L;

                String composedResponse = "api_key=" + URLEncoder.encode(apiKey, "utf-8")
                        + "&call_id=" + callId
                        + "&method=" + URLEncoder.encode(method, "utf-8")
                        + "&nonce=" + URLEncoder.encode(nonce, "utf-8")
                        + "&access_token=" + URLEncoder.encode(accessToken, "utf-8")
                        + "&v=" + URLEncoder.encode(version, "utf-8");

                response = composedResponse.getBytes("utf-8");
            }

            String authenticationText = "";

            if (response != null){
                authenticationText = Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
            }
            // Send the authentication to the server
            getSASLAuthentication().send(new Response(authenticationText));
        }

        private Map<String, String> getQueryMap(String query) {
            Map<String, String> map = new HashMap<String, String>();
            String[] params = query.split("\\&");

            for (String param : params) {
                String[] fields = param.split("=", 2);
                map.put(fields[0], (fields.length > 1 ? fields[1] : null));
            }
            return map;
        }
    }
public void connecttoff()抛出XMPPException{
ConnectionConfiguration config=新的ConnectionConfiguration(“chat.facebook.com”,5222);
SASLAuthentication.registerSASLMechanism(“X-FACEBOOK-PLATFORM”,SASLXFacebookPlatformMechanism.class);
Saslauthentification.supportSASLMechanism(“X-FACEBOOK-PLATFORM”,0);
config.setaslauthenticationenabled(true);
config.setSecurityMode(SecurityMode.required);
config.setSendPresence(假);
XMPPConnection xmpp=新的XMPPConnection(配置);
试一试{
xmpp.connect();
xmpp.login(Session.getActiveSession().getApplicationId(),Session.getActiveSession().getAccessToken(),“应用程序”);
//发送聊天信息
ChatManager ChatManager=xmpp.getChatManager();
Chat newChat=chatmanager.createChat(@Chat.facebook.com),newmessagelistener(){
@凌驾
public void processMessage(聊天、消息消息消息){
Log.d(“测试”,“消息发送=”+msg);
}
});
sendMessage(“Cowdy!”);
//拿到名册
花名册=xmpp.get花名册();
集合条目=花名册.getEntries();
System.out.println(“已连接!”);
System.out.println(“\n\n”+entries.size()+“buddy:”);
对于(排班条目:条目){
Log.i(“test”,entry.getName());
Log.i(“test”,entry.getUser());
}
}捕获(XMPPException e){
xmpp.disconnect();
e、 printStackTrace();
}
}
SASLXFacebookPlatformMechanism.java

public void connectToFb() throws XMPPException {        
        ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
        SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
        SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
        config.setSASLAuthenticationEnabled(true);
        config.setSecurityMode(SecurityMode.required);
        config.setSendPresence(false);
        XMPPConnection xmpp = new XMPPConnection(config);
        try {
            xmpp.connect();
            xmpp.login(Session.getActiveSession().getApplicationId(), Session.getActiveSession().getAccessToken(), "Application");

            //send a chat message           
            ChatManager chatmanager = xmpp.getChatManager();
            Chat newChat = chatmanager.createChat("<jabber-id-here>@chat.facebook.com", new MessageListener() {
                @Override
                public void processMessage(Chat chat, Message msg) {
                    Log.d("test", "message sent = "+ msg);
                }
            });
            newChat.sendMessage("Cowdy!");    

            //get roster  
            Roster roster = xmpp.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
            System.out.println("Connected!");
            System.out.println("\n\n" + entries.size() + " buddy(ies):");
            for (RosterEntry entry : entries) {
                Log.i("test", entry.getName());
                Log.i("test", entry.getUser());
            }
        } catch (XMPPException e) {
            xmpp.disconnect();
            e.printStackTrace();
        }
    }
public class SASLXFacebookPlatformMechanism extends SASLMechanism {

        public static final String NAME = "X-FACEBOOK-PLATFORM";
        private String apiKey = "";
        private String accessToken = "";


        /**
         * Constructor.
         */
        public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication) {
            super(saslAuthentication);
        }

        @Override
        protected void authenticate() throws IOException, XMPPException {
            // Send the authentication to the server
            getSASLAuthentication().send(new AuthMechanism(getName(), ""));
        }

        @Override
        public void authenticate(String apiKey, String host, String accessToken) throws IOException, XMPPException {
            this.apiKey = apiKey;
            this.accessToken = accessToken;
            this.hostname = host;

            String[] mechanisms = { "DIGEST-MD5" };
            Map<String, String> props = new HashMap<String, String>();
            this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
            authenticate();
        }

        @Override
        protected String getName() {
            return NAME;
        }

        @Override
        public void challengeReceived(String challenge) throws IOException {
            byte[] response = null;

            if (challenge != null) {
                String decodedChallenge = new String(Base64.decode(challenge));
                Map<String, String> parameters = getQueryMap(decodedChallenge);

                String version = "1.0";
                String nonce = parameters.get("nonce");
                String method = parameters.get("method");

                long callId = new GregorianCalendar().getTimeInMillis() / 1000L;

                String composedResponse = "api_key=" + URLEncoder.encode(apiKey, "utf-8")
                        + "&call_id=" + callId
                        + "&method=" + URLEncoder.encode(method, "utf-8")
                        + "&nonce=" + URLEncoder.encode(nonce, "utf-8")
                        + "&access_token=" + URLEncoder.encode(accessToken, "utf-8")
                        + "&v=" + URLEncoder.encode(version, "utf-8");

                response = composedResponse.getBytes("utf-8");
            }

            String authenticationText = "";

            if (response != null){
                authenticationText = Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
            }
            // Send the authentication to the server
            getSASLAuthentication().send(new Response(authenticationText));
        }

        private Map<String, String> getQueryMap(String query) {
            Map<String, String> map = new HashMap<String, String>();
            String[] params = query.split("\\&");

            for (String param : params) {
                String[] fields = param.split("=", 2);
                map.put(fields[0], (fields.length > 1 ? fields[1] : null));
            }
            return map;
        }
    }
公共类SASLXFacebookPlatformMechanism扩展了SASLMechanism{
公共静态最终字符串NAME=“X-FACEBOOK-PLATFORM”;
私有字符串apiKey=“”;
私有字符串accessToken=“”;
/**
*构造器。
*/
公共SASLXFacebookPlatformMechanism(SASLAuthentication SASLAuthentication){
超级(saslAuthentication);
}
@凌驾
受保护的void authenticate()引发IOException,xmppeException{
//将身份验证发送到服务器
getSASLAuthentication().send(新的身份验证机制(getName(),“”);
}
@凌驾
公共无效身份验证(字符串apiKey、字符串主机、字符串accessToken)引发IOException、XMPPException{
this.apiKey=apiKey;
this.accessToken=accessToken;
this.hostname=host;
字符串[]机制={“摘要-MD5”};
Map props=newhashmap();
this.sc=Sasl.createSaslClient(机制,null,“xmpp”,主机,道具,this);
验证();
}
@凌驾
受保护的字符串getName(){
返回名称;
}
@凌驾
public void challengeReceived(字符串质询)引发IOException{
字节[]响应=null;
if(质询!=null){
String decodedChallenge=新字符串(Base64.decode(challenge));
映射参数=getQueryMap(decodedChallenge);
字符串version=“1.0”;
字符串nonce=parameters.get(“nonce”);
String方法=parameters.get(“方法”);
long callId=new gregorianalendar().getTimeInMillis()/1000L;
字符串composedResponse=“api_key=“+URLCoder.encode(apiKey,“utf-8”)
+“&call_id=“+callId
+“&method=“+urlcoder.encode(方法“utf-8”)
+“&nonce=“+urlcoder.encode(nonce,“utf-8”)
+“&access_token=“+urlcoder.encode(accessToken,“utf-8”)
+“&v=“+URLEncoder.encode(版本,“utf-8”);
response=composedResponse.getBytes(“utf-8”);
}
字符串authenticationText=“”;
if(响应!=null){
authenticationText=Base64.encodeBytes(响应,Base64.Don_BREAK_line);
}
//将身份验证发送到服务器
getSASLAuthentication().send(新响应(authenticationText));
}
私有映射getQueryMap(字符串查询){
Map Map=newhashmap();
字符串[]params=query.split(“\\&”);
for(字符串参数:params){
字符串[]字段=参数拆分(“=”,2);
map.put(字段[0],(fields.length>1?字段[1]:null));
}
返回图;
}
}

使用SASL/Plain的身份验证流(当提供用户名和密码时)