tencent cloud

Java SDK
Last updated:2026-01-30 15:02:25
Java SDK
Last updated: 2026-01-30 15:02:25

Feature Overview

The Eclipse Paho Java Client is an MQTT client library (MQTT Java Client) written in Java, applicable to JVMs or other Java-compatible platforms such as Android.
Eclipse Paho Java Client provides MqttAsyncClient and MqttClient with async and synchronous APIs.

Cloud Resource Preparation

Please refer to resource creation operation steps to complete cloud resource preparation.

Environment Preparation

Installing Paho Java Via Maven

MQTT 5 Paho SDK
MQTT 3.1.1 Paho SDK
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.mqttv5.client</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>

Example Code

MQTT 5
MQTT 5 TLS
MQTT 3.1.1
MQTT 3.1.1 TLS
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import java.nio.ByteBuffer;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;

public class QuickStart {
public static void main(String[] args) throws MqttException, InterruptedException {
// Get access point from MQTT console:
// Users who implement VPC network integration via Private Link use private network access points;
// Users accessing over public network, underwrite public network security policy permission, program execution machines have public network access;
String serverUri = "tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883";

// A valid Client Identifier contains digits 0-9, lowercase English letters a-z, and uppercase English letters A-Z, with a total length of 1-23 characters
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
String clientId = "QuickStart";

// Create account on the console under the Authentication Tab, copy username and password
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// MQTT topic
String pubTopic = "home/test";
String[] topicFilters = new String[]{pubTopic, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence());
client.setTimeToWait(3000);
MqttConnectionOptions options = new MqttConnectionOptions();
options.setUserName(username);
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
options.setCleanStart(true);
options.setAutomaticReconnect(true);

client.setCallback(new MqttCallback() {
@Override
public void disconnected(MqttDisconnectResponse response) {
System.out.println("Disconnected: " + response.getReasonString());
}

@Override
public void mqttErrorOccurred(MqttException e) {
e.printStackTrace();
}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
byte[] payload = message.getPayload();
String content;
if (4 == payload.length) {
ByteBuffer buf = ByteBuffer.wrap(payload);
content = String.valueOf(buf.getInt());
} else {
content = new String(payload, StandardCharsets.UTF_8);
}
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n",
topic, message.getQos(), content);
}

@Override
public void deliveryComplete(IMqttToken token) {

}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
// Subscribe
client.subscribe(topicFilters, qos);
} catch (MqttException e) {
e.printStackTrace();
}
}

@Override
public void authPacketArrived(int i, MqttProperties properties) {
}
});

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(pubTopic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.eclipse.paho.mqttv5.common.packet.UserProperty;

public class QuickStartTls {

public static SSLSocketFactory buildSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, null, null);
return ctx.getSocketFactory();
}

public static void main(String[] args) throws Exception {
// Get access point from MQTT console:
// Users who implement VPC network integration via Private Link use private network access points;
// Users accessing over public network, underwrite public network security policy permission, program execution machines have public network access;
String serverUri = "ssl://mqtt-xxx.mqtt.tencenttdmq.com:8883";

// A valid Client Identifier contains digits 0-9, lowercase English letters a-z, and uppercase English letters A-Z, with a total length of 1-23 characters
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
String clientId = "QuickStartTls";

// Create account on the console under the Authentication Tab, copy username and password
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// MQTT topic
String topicName = "home/test";
String[] topicFilters = new String[]{topicName, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence());
client.setTimeToWait(3000);
MqttConnectionOptions options = new MqttConnectionOptions();
options.setSocketFactory(buildSSLSocketFactory());
options.setHttpsHostnameVerificationEnabled(false);
options.setUserName(username);
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
options.setCleanStart(true);
options.setAutomaticReconnect(true);

client.setCallback(new MqttCallback() {
@Override
public void disconnected(MqttDisconnectResponse response) {
System.out.println("Disconnected: " + response.getReasonString());
}

@Override
public void mqttErrorOccurred(MqttException e) {
e.printStackTrace();
}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
byte[] payload = message.getPayload();
String content;
if (4 == payload.length) {
ByteBuffer buf = ByteBuffer.wrap(payload);
content = String.valueOf(buf.getInt());
} else {
content = new String(payload, StandardCharsets.UTF_8);
}
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n",
topic, message.getQos(), content);
}

@Override
public void deliveryComplete(IMqttToken token) {

}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
// Subscribe
IMqttToken token = client.subscribe(topicFilters, qos);
int[] reasonCodes = token.getReasonCodes();
for (int i = 0; i < reasonCodes.length; i++) {
System.out.printf("Subscribed to topic %s with QoS=%d, Granted-QoS: %d%n",
topicFilters[i], qos[i], reasonCodes[i]);
}

if (token.isComplete()) {
List<UserProperty> userProperties = token.getResponseProperties().getUserProperties();
printUserProperties(userProperties);
}
} catch (MqttException e) {
e.printStackTrace();
}
}

@Override
public void authPacketArrived(int i, MqttProperties properties) {
}
});

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(topicName, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}

static void printUserProperties(List<UserProperty> userProperties) {
if (null != userProperties) {
for (UserProperty userProperty : userProperties) {
System.out.printf("User property: %s = %s%n", userProperty.getKey(), userProperty.getValue());
}
}
}
}


import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class QuickStart {
public static void main(String[] args) throws MqttException, InterruptedException {
// Get access point from MQTT console:
// Users who implement VPC network integration via Private Link use private network access points;
// Users accessing over public network, underwrite public network security policy permission, program execution machines have public network access;
String serverUri = "tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883";

// A valid Client Identifier contains digits 0-9, lowercase English letters a-z, and uppercase English letters A-Z, with a total length of 1-23 characters
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
String clientId = "QuickStart";

// Create account on the console under the Authentication Tab, copy username and password
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// Confirm the first-level topic "home" has been created in the MQTT console
String pubTopic = "home/test";
String[] topicFilters = new String[]{pubTopic, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

try (MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence())) {
client.setTimeToWait(3000);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setCleanSession(true);
options.setAutomaticReconnect(true);

MqttCallback callback = new MqttCallback(client, topicFilters, qos);
client.setCallback(callback);

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(pubTopic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}

static class MqttCallback implements MqttCallbackExtended {

private final MqttClient client;

private final String[] topicFilters;
private final int[] qos;

public MqttCallback(MqttClient client, String[] topicFilters, int[] qos) {
this.client = client;
this.topicFilters = topicFilters;
this.qos = qos;
}

public void messageArrived(String topic, MqttMessage message) {
System.out.printf("Message arrived, topic=%s, QoS=%d, Dup=%s, Retained=%s, content=[%s]%n",
topic, message.getQos(), message.isDuplicate(), message.isRetained(),
new String(message.getPayload(), StandardCharsets.UTF_8));
}

public void connectionLost(Throwable cause) {
System.out.println("connectionLost: " + cause.getMessage());
}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
client.subscribe(topicFilters, qos);
System.out.printf("Subscribed %d topics%n", topicFilters.length);
} catch (MqttException e) {
e.printStackTrace();
}
}

public void deliveryComplete(IMqttDeliveryToken token) {
System.out.printf("Delivery completed: packet-id=%d%n", token.getMessageId());
}
}
}
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class QuickStartTls {

public static SSLSocketFactory buildSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, null, null);
return ctx.getSocketFactory();
}

public static void main(String[] args) throws MqttException, InterruptedException, NoSuchAlgorithmException, KeyManagementException {

// Get access point from MQTT console:
// Users who implement VPC network integration via Private Link use private network access points;
// Users accessing over public network, underwrite public network security policy permission, program execution machines have public network access;
String serverUri = "ssl://mqtt-xxxx.mqtt.tencenttdmq.com:8883";
// A valid Client Identifier contains digits 0-9, lowercase English letters a-z, and uppercase English letters A-Z, with a total length of 1-23 characters
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
String clientId = "ClientQuickStartTls";

// Create account on the console under the Authentication Tab, copy username and password
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// Confirm the first-level topic "home" has been created in the MQTT console
String topic = "home/test";

String[] topicFilters = new String[]{"home/test"};
int[] qos = new int[]{1};

int total = 16;

try (MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence())) {
client.setTimeToWait(3000);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setSocketFactory(buildSSLSocketFactory());
options.setHttpsHostnameVerificationEnabled(false);
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setCleanSession(true);
options.setAutomaticReconnect(true);
client.connect(options);

client.setCallback(new MqttCallback(client, topicFilters, qos));

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes());
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(topic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(1);
}

TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}

static class MqttCallback implements MqttCallbackExtended {

private final MqttClient client;

private final String[] topicFilters;
private final int[] qos;

public MqttCallback(MqttClient client, String[] topicFilters, int[] qos) {
this.client = client;
this.topicFilters = topicFilters;
this.qos = qos;
}

public void messageArrived(String topic, MqttMessage message) {
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n", topic, message.getQos(),
new String(message.getPayload(), StandardCharsets.UTF_8));
}

public void connectionLost(Throwable cause) {
System.out.println("connectionLost: " + cause.getMessage());
}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connect" + serverURI);
try {
client.subscribe(topicFilters, qos);
System.out.printf("Subscribed %d topics%n", topicFilters.length);
} catch (MqttException e) {
e.printStackTrace();
}
}

public void deliveryComplete(IMqttDeliveryToken token) {
System.out.printf("Delivery completed: packet-id=%d%n", token.getMessageId());
}
}
}
Parameter
Description
pubTopic
Destination topic for the message to be published.
A message topic can contain multiple levels, separated by '/'. The level 1 topic must be created in the console Topic Tab page. For details, refer to Topic Names and Topic Filters.
topicFilters
One or more subscription expressions.
Subscription expressions can contain Wildcards. For details, refer to Topic Names and Topic Filters.
qos
Service quality array, array length must be consistent with Topic Filters data consistency.
The most commonly used QoS is 1, which means deliver At Least Once. For details, see Quality of Service levels and protocol flows.
serverUri
MQTT instance connection point, copied from the Basic Information > Access Information module of the target cluster on the console. The location is as shown below.
Standard access point: tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883
TLS access point: ssl://mqtt-xxx.mqtt.tencenttdmq.com:8883
Standard WebSocket access point: ws://mqtt-xxx.mqtt.tencenttdmq.com:80/mqtt
TLS WebSocket access point: wss://mqtt-xxx.mqtt.tencenttdmq.com:443/mqtt



clientId
Unique device identifier: such as vehicle identification number (VIN), product serial number.
A valid Client Identifier contains digits 0-9, lowercase English letters a-z, and uppercase English letters A-Z, with a total length of 1-23 characters. For details, refer to Client Identifier.
username
Connection Username, copy it on the authentication management page of the cluster detail page in the console.



password
Password matching the Connection Username, copy it on the authentication management page of the cluster details page in the console.


Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback