This article describes how to use the Paho Message Queuing Telemetry Transport (MQTT)
library for Java to connect to IoT Platform and exchange messages with IoT Platform.
Prepare the development environment
In this example, the development environment consists of the following components:
Download the Paho MQTT library for Java
Add dependencies to the Maven project based on the version of the MQTT protocol.
- MQTT 3.1 and 3.1.1
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
- MQTT 5.0
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.mqttv5.client</artifactId>
<version>1.2.5</version>
</dependency>
Connect to IoT Platform
- Click MqttSign.java to obtain the source code provided by Alibaba Cloud to calculate the MQTT connection
parameters.
The MqttSign.java file defines the MqttSign class.
- Open IntelliJ IDEA and create a project.
- Import the MqttSign.java file into the project.
- In the project, add a program file that can connect a device to IoT Platform.
You must write a program to use the MqttSign class in the MqttSign.java file to calculate the parameters that are used to establish an MQTT connection to
IoT Platform.
This section provides the development instructions and sample code.
- Use the MqttSign class to calculate the MQTT connection parameters.
String productKey = "a1X2bEn****";
String deviceName = "example1";
String deviceSecret = "ga7XA6KdlEeiPXQPpRbAjOZXwG8y****";
// Calculate the MQTT connection parameters.
MqttSign sign = new MqttSign();
sign.calculate(productKey, deviceName, deviceSecret);
System.out.println("username: " + sign.getUsername());
System.out.println("password: " + sign.getPassword());
System.out.println("clientid: " + sign.getClientid());
- Create a Paho MQTT client to connect to IoT Platform.
// Specify the domain name for connecting to IoT Platform.
String port = "443";
String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;
// Create a Paho MQTT client.
MqttClient sampleClient = new MqttClient(broker, sign.getClientid(), persistence);
// Set the MQTT connection parameters.
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setKeepAliveInterval(180);
connOpts.setUserName(sign.getUsername());
connOpts.setPassword(sign.getPassword().toCharArray());
sampleClient.connect(connOpts);
System.out.println("Broker: " + broker + " Connected");
- Publish messages.
The following sample code is used to report the LightSwitch property of a TSL model.
// Publish messages by using Paho MQTT.
String topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
String content = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":1}}";
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(0);
sampleClient.publish(topic, message);
If you use MQTT 5.0, you can add the following sample code to publish messages that
contain custom properties.
// MQTT 5.0 new feature: Report custom properties.
MqttProperties properties = new MqttProperties();
List<UserProperty> userPropertys = new ArrayList<>();
userPropertys.add(new UserProperty("key1","value1"));
properties.setUserProperties(userPropertys);
// MQTT 5.0 new feature: Set the request and response mode.
properties.setCorrelationData("requestId12345".getBytes());
properties.setResponseTopic("/" + productKey + "/" + deviceName + "/user/get");
message.setProperties(properties);
// By default, Paho SDK that supports MQTT 5.0 uses topic aliases.
sampleClient.publish(topic, message);
For more information about the TSL data format, see Device properties, events, and services.
For more information about how to use custom topics for communication, see What is a topic?
- Subscribe to a topic to obtain messages from IoT Platform.
In this example, you subscribe to the topic to which IoT Platform returns response
messages after the property values are reported.
class MqttPostPropertyMessageListener implements IMqttMessageListener {
@Override
public void messageArrived(String var1, MqttMessage var2) throws Exception {
System.out.println("reply topic : " + var1);
System.out.println("reply payload: " + var2.toString());
}
}
...
// Subscribe to a message topic by using Paho MQTT.
String topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
sampleClient.subscribe(topicReply, new MqttPostPropertyMessageListener());
For more information about the communication methods of devices, servers, and IoT
Platform, see Communication methods.
- Compile the project.
Demo
The demo code demonstrates how to connect a device to IoT Platform.
- Download the demo package and decompress it.
- Open IntelliJ IDEA and import the sample project aiot-java-demo in the demo package.
- In the src/main/java/com.aliyun.iot directory, replace the device information with your device information in the App or Mqtt5App file.
Note If you use MQTT 3.1 or 3.1.1, replace the device information in the App file. If you use MQTT 5.0, replace the device information in the Mqtt5App file.
- Run the App or Mqtt5App program.
The following figure shows the success logs.

Log on to the IoT Platform console.View device status and logs.
Error codes
If a device fails to establish an MQTT connection to IoT Platform, you can troubleshoot
the issue based on the error code. For more information about the error codes that
may be returned by IoT Platform, see Troubleshooting.