Smack 是一個用于連接和操作 XMPP(可擴展消息與出席協議)的 Java 庫。要進行身份驗證,您需要提供正確的用戶名和密碼。以下是如何使用 Smack 進行身份驗證的簡單示例:
pom.xml
文件中添加以下依賴項:<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-java7</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-tcp</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-extensions</artifactId>
<version>4.4.4</version>
</dependency>
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
public class SmackExample {
public static void main(String[] args) {
String serviceName = "your-xmpp-server.com";
int port = 5222;
String username = "your-username";
String password = "your-password";
// 創建連接配置
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setXmppDomain(serviceName)
.setHost(serviceName)
.setPort(port)
.build();
// 創建連接
Connection connection = new XMPPTCPConnection(config);
try {
// 連接到服務器
connection.connect();
System.out.println("Connected to the XMPP server.");
// 登錄成功,可以進行其他操作,如發送消息、訂閱等
} catch (XMPPException e) {
e.printStackTrace();
} finally {
// 斷開連接
if (connection != null) {
connection.disconnect();
}
}
}
}
請確保將 your-xmpp-server.com
、your-username
和 your-password
替換為您的實際 XMPP 服務器地址、用戶名和密碼。運行此示例后,如果身份驗證成功,您將看到 “Connected to the XMPP server.” 消息。