Updated on 2023-10-18 GMT+08:00

Java Demo Usage Guide

This topic uses Java as an example to describe how to connect an MQTTS client to the platform and receive subscribed messages from the platform.

Prerequisites

You have installed IntelliJ IDEA by following the instructions provided in For details about the installation, see Installing IntelliJ IDEA.

Installing IntelliJ IDEA

  1. Go to the IntelliJ IDEA website to download and install a desired version. The following uses 64-bit IntelliJ IDEA 2019.2.3 Ultimate as an example.

  2. After the download is complete, run the installation file and install Node.js as prompted.

Importing Sample Code

  1. Download the Java demo.
  2. Open the IDEA developer tool and click Import Project.

  3. Select the downloaded Java demo and click Next.

  4. Import the sample code.

Establishing a Connection

  1. Set the access address and authentication parameters.

    // Address for connecting the MQTT client to the platform. Replace it with the MQTT access domain name in "Connection Configuration Parameters".
    private String serverAddress = "${UUCID}.st1.iotda-app.cn-north-4.myhuaweicloud.com";
    //Access credential. Replace it with the access credential obtained in "Obtaining the MQTT Access Credential".
    private static String accessKey = "accessKey";
    private static String accessCode = "accessCode";
    // Topic for receiving data. Replace it with the topic used for rule action creation.
    private static String subscribeTopic = "userTopic";

    For details about the parameters in the demo, see Connection Configuration Parameters.

  2. Run the sample code and check whether the subscription is successful based on the following log information:

    • Successful subscription
      Figure 1 Successful subscription
    • Failed subscription
      1. The username or password is incorrect.
        Figure 2 Incorrect username or password
      2. The topic does not exist.
        Figure 3 The topic does not exist

Receiving Data

After topic subscription, when a device reports data and a rule is triggered, the MQTT client can receive the forwarded data. The following figure shows the logs generated when the forwarded data is received.

Figure 4 Receiving the forwarded data