Use the Java SDK

Updated at:

The IoT Platform Java SDK lets you manage IoT Platform resources from Java programs. You can add the SDK as a Maven dependency or install it from a local package.

Install the SDK

  1. Install the Java development environment.

    Download and install the Java development environment from the official Java website. Ensure that you install Java 8 or a later version.

  2. Install the IoT Java SDK.

    1. Go to the official Apache Maven website to download the Maven software.

    2. Add Maven project dependencies.

      Important

      The following version is an example. For more information about the latest version, see how to install the SDK for IoT Platform in the OpenAPI Portal.

      • Maven dependency coordinates for the IoT Java SDK:

        <!-- https://mvnrepository.com/artifact/com.aliyun/iot20180120 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>iot20180120</artifactId>
            <version>4.2.0</version>
        </dependency>
      • Maven dependency coordinates for the Alibaba Cloud Java SDK common package:

        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-openapi</artifactId>
          <version>0.2.2</version>
        </dependency>

For more information about the Java SDK source code, see alibabacloud-java-sdk.

Initialize the SDK

  1. Create a Config object named config to store the SDK initialization parameters, such as the AccessKey ID, AccessKey secret, and region ID.

  2. Create a Client object instance named client. Call the com.aliyun.iot20180120.Client(config) method to load the SDK information from config and initialize the client.

    The Request and Response parameters for subsequent API calls are in com.aliyun.iot20180120.models.

The following example initializes the SDK for the China (Shanghai) region. Replace the endpoint with the one for the region where your IoT Platform service is deployed.

Config config = new Config()
    // Your AccessKey ID.
    .setAccessKeyId(accessKeyId)
    // Your AccessKey secret.
    .setAccessKeySecret(accessKeySecret);
// The endpoint to access.
config.endpoint = "iot.cn-beijing.aliyuncs.com";

Client client = new Client(config);

Parameter

Description

accessKeyId

The AccessKey ID for your Alibaba Cloud account.

You can create or view your AccessKey pair on the AccessKey Management page in the Alibaba Cloud console.

accessKeySecret

The AccessKey secret for your Alibaba Cloud account.

regionId

The region ID of your IoT Platform service, used to construct the endpoint in the format: iot.${RegionId}.aliyuncs.com.

You can view the current service region in the upper-left corner of the IoT Platform console.

For more information about how to specify a region ID, see Regions and zones.

Important

To avoid security risks associated with hard-coding AccessKey credentials in your code, use environment variables to manage your AccessKey pair.

Add the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to your operating system and set them to your AccessKey ID and AccessKey secret.

You can retrieve the credentials in code as follows:

  • System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")

  • System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")

Make a call

The IoT Platform cloud SDK provides two classes for each API: ${API name}+"Request" and ${API name}+"Response". These classes represent the API request and response.

Call steps

  1. Initialize the SDK client. For more information, see SDK Initialization.

  2. Create a ${API name}+"Request" object instance named request for the API call.

  3. Call the set+${Request parameter name} method on the request object to set the required request parameters.

  4. Create a ${API name}+"Response" object instance named response. Call the ${API name}(request) method on the client object to get the response. The response includes the body and headers from the server.

  5. Call the get+${Response parameter name} method on the body member of the response object to retrieve a response parameter value.

    For example, response.getbody.getSuccess() retrieves the success flag. Success is a common response parameter. Other common response parameters include RequestId, ErrorMessage, and Code.

  6. Use the catch() method to handle exceptions.

For the full list of IoT Platform cloud APIs, see API list. For request and response parameter descriptions, see the documentation for each API.

The following example uses the Pub API to publish a message to a topic. For request parameter details, see Pub.

Important

In the following code, iotInstanceId is the instance ID. For more information about instances, see Instance overview.

For information about how to purchase an instance, see Purchase an Enterprise instance.

For information about how to obtain an instance ID, see IoT Platform instance-related FAQ.

PubRequest request = new PubRequest()
    .setIotInstanceId("${iotInstanceId}")
    .setProductKey("${productKey}")
    .setMessageContent(Base64.getEncoder().encodeToString("hello world".getBytes()))
    .setTopicFullName("/${productKey}/${deviceName}/user/get")
    .setQos(0);// QoS 0 and QoS 1 are supported. 
try {
    PubResponse response = client.pub(request);
    // The response contains the body and headers from the server-side. 
    // Get the request ID of this call.
    System.out.println(response.getBody().getRequestId());
    // Check whether the call is successful.
    System.out.println(response.getBody().getSuccess());
    
    // The call is successful.
    if (response.getBody().getSuccess()) {
        // Get the message ID from the cloud.
        System.out.println(response.getBody().getMessageId());
        
        // Implement your business logic.
        
    } else {
    // The call failed.            
        // Get the error code for the failed call.
        System.out.println(response.getBody().getCode());
        // Get the error message for the failed call.
        System.out.println(response.getBody().getErrorMessage());
     }
} catch (TeaException error) {
    // A server-side business exception occurred.
    System.out.println(error.getCode());
    System.out.println(error.getMessage());
} catch (Exception e) {
    // Other runtime exceptions occurred.
    e.printStackTrace();
}

Complete sample code

Note

Replace the parameter values with your own values based on the descriptions earlier in this topic.

import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.PubRequest;
import com.aliyun.iot20180120.models.PubResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import java.util.Base64;

public class IotSdkDemo {
    /**
     * Initialize the client using an AccessKey ID and AccessKey secret.
     */
    private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Your AccessKey ID.
                .setAccessKeyId(accessKeyId)
                // Required. Your AccessKey secret.
                .setAccessKeySecret(accessKeySecret);
        // For the endpoint, see https://api.aliyun.com/product/Iot
        config.endpoint = "iot.cn-beijing.aliyuncs.com";
        return new Client(config);
    }

    public static void main(String[] args) {
        try {
            Client client = createClient(accessKey, accessKeySecret);
            PubRequest request = new PubRequest()
                .setIotInstanceId("${iotInstanceId}")
                .setProductKey("${productKey}")
                .setMessageContent(Base64.getEncoder().encodeToString("hello world".getBytes()))
                .setTopicFullName("/${productKey}/${deviceName}/user/get")
                .setQos(0);// QoS 0 and QoS 1 are supported. 
            
            PubResponse response = client.pub(request);            
            // Get the request ID of this call.
      System.out.println(response.getBody().getRequestId());
      // Check whether the call is successful.
      System.out.println(response.getBody().getSuccess());
            
         // The call is successful.
       if (response.getBody().getSuccess()) {
          // Get the message ID from the cloud.
          System.out.println(response.getBody().getMessageId());
        
          // Implement your business logic.
      } else {
       // The call failed.            
          // Get the error code for the failed call.
             System.out.println(response.getBody().getCode());
          // Get the error message for the failed call.
          System.out.println(response.getBody().getErrorMessage());
      }
        } catch (TeaException error) {
            // A server-side business exception occurred.
      System.out.println(error.getCode());
      System.out.println(error.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Appendix: Sample code

Visit the IoT Platform Cloud SDK Example Center to view or download sample code for API calls. The examples cover SDKs in Java, Python, PHP, Node.js, Go, C++, and .NET.

The Alibaba Cloud OpenAPI Developer Portal provides an online API debugging tool. On the API debugging page, you can search for and test API calls. The portal automatically generates SDK sample code in different languages based on the parameters you enter. View the generated code on the SDK Example tab and the response on the Call Result tab.