Java SDK call examples

Updated at:

Call a preset metric API by using the Java SDK to query device statistics from IoT Platform data service.

Prerequisites

  • To call a preset metric API, make sure that you have created a product and a device, and backed up the data. For more information, see preset metric API.

  • To call a product data API or a custom service API, make sure that you have created the required API. For more information, see product data API and custom service API.

For more information, see Manage and use APIs.

Install the SDK

  1. Install the Java development environment.

    Download the Java development environment from the official website and install it.

  2. Install the IoT Java SDK.

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

    2. Install the IoT Java SDK.

              <dependency>
                  <groupId>com.aliyun</groupId>
                  <artifactId>tea-openapi</artifactId>
                  <version>0.0.11</version>
              </dependency>
              <dependency>
                  <groupId>com.aliyun</groupId>
                  <artifactId>iot20180120</artifactId>
                  <version>1.1.0</version>
              </dependency>

Make an API call

The following sample code calls a preset metric API from the data service to query historical device count statistics.

Important

A single Alibaba Cloud account can make up to 100 queries per second (QPS) to data service APIs.

import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.aliyun.teaopenapi.models.Config;
public class JavaDemo {
    /**
     * Use an AccessKey ID and an AccessKey Secret to initialize the client.
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        // Your endpoint.
        config.setEndpoint("iot.cn-shanghai.aliyuncs.com");
        return new Client(config);
    }
    public static void main(String[] args_) throws Exception {
        // Your AccessKey ID and AccessKey Secret.
        Client client = JavaDemo.createClient("yourAccessKeyID", "yourAccessKeySecret"));
        ListAnalyticsDataRequest request = new ListAnalyticsDataRequest();
        // Your API path.
        request.setApiPath("/iot-cn-npk1v******/system/query/hist_dev_cnt_stat");
        // The ID of the instance that hosts your API.
        request.setIotInstanceId("iot-cn-npk1v******");
        // Pagination parameter: page number.
        request.setPageNum(1);
        // Pagination parameter: page size.
        request.setPageSize(100);
        List<ListAnalyticsDataRequest.ListAnalyticsDataRequestCondition> conditions = new ArrayList<>();
        // Business-related request parameters. For information about configuring a Condition, see the parameter descriptions that follow.
        ListAnalyticsDataRequest.ListAnalyticsDataRequestCondition condition = new ListAnalyticsDataRequest
                .ListAnalyticsDataRequestCondition();
        condition.setFieldName("__instance_id__");
        condition.setOperate("=");
        condition.setValue("iot-public");
        conditions.add(condition);
        ListAnalyticsDataRequest.ListAnalyticsDataRequestCondition condition1 = new ListAnalyticsDataRequest
                .ListAnalyticsDataRequestCondition();
        condition1.setFieldName("entityId");
        condition1.setOperate("=");
        condition1.setValue("all");
        conditions.add(condition1);
        ListAnalyticsDataRequest.ListAnalyticsDataRequestCondition condition2 = new ListAnalyticsDataRequest
                .ListAnalyticsDataRequestCondition();
        condition2.setFieldName("statDate");
        condition2.setOperate("=");
        condition2.setValue("20210221");
        conditions.add(condition2);
        request.setCondition(conditions);
        ListAnalyticsDataResponse listAnalyticsDataResponse = client.listAnalyticsData(request);
        System.out.println(JSON.toJSONString(listAnalyticsDataResponse));    
  }
}
  • System request parameters:

    Parameter

    Type

    Required

    Example

    Description

    accessKeyId

    String

    Yes

    LTAI****************

    Hover over your profile picture and click AccessKey Management to obtain your AccessKey ID and AccessKey Secret.

    Note

    If you use a RAM user, you must grant the RAM user permissions to manage IoT Platform (AliyunIOTFullAccess). Otherwise, the connection will fail. For more information, see Grant a RAM user permissions to access IoT Platform.

    accessKeySecret

    String

    Yes

    yourAccessKeySecret

    Endpoint

    String

    Yes

    iot.cn-shanghai.aliyuncs.com

    The endpoint of the Alibaba Cloud service. The region must match the region of your IoT Platform product.

    In this example, the region is China (Shanghai).

    apiPath

    String

    Yes

    /iot-cn-npk1v******/system/query/hist_dev_cnt_stat

    The API path. On the data service page, find your API and click View to obtain it. For more information, see Manage APIs.

    iotInstanceId

    String

    Yes

    iot-cn-npk1u******

    The ID of the IoT Platform instance that hosts the API.

    pageNum

    Integer

    Required if pagination is enabled

    10

    The page number.

    pageSize

    Integer

    Required if pagination is enabled

    100

    The number of entries to return on each page. Maximum value: 100.

  • Business-related request parameters:

    Parameter

    Type

    Required

    Description

    Related code

    FieldName

    String

    Yes

    The name of the request parameter.

     condition.setFieldName("entityId");

    Operate

    String

    Yes

    The operator for the request parameter. Valid values:

    • =: The parameter must have the specified value.

    • BETWEEN: The parameter value must be within the specified range.

    • IN: The parameter value must be one of the specified values.

    • !=: The parameter must not have the specified value.

     condition.setOperate("=");

    Value

    String

    No

    The value to assign to the request parameter.

    Important

    This parameter is required unless the operator is BETWEEN.

     condition.setValue("all");

    BetweenStart

    String

    No

    The start of the value range for the request parameter.

    Important

    This parameter is required only when the operator is BETWEEN.

     condition.setBetweenStart("0");

    BetweenEnd

    String

    No

    The end of the value range for the request parameter.

    Important

    This parameter is required only when the operator is BETWEEN.

    condition.setBetweenEnd("100");

    On the API details page, check the request parameters to determine how many condition objects to configure. For more information about how to view API request parameters, see Manage APIs.

    In the sample code, the API has three request parameters, __instance_id__, entityId, and statDate, which correspond to condition, condition1, and condition2, respectively.

Results

  • Success:

    You can view detailed descriptions of response parameters on the API details page. For more information, see Manage and use APIs.

    The following example shows a successful response. The response includes device count statistics for the public instance on February 21, 2021.

    {
        "body": {
            "data": {
                "hasNext": false,
                "pageNum": 1,
                "pageSize": 100,
                "resultJson": "[{\"statDate\":\"20210221\",\"actDevCnt\":2942,\"onlineDevCntCompare\":0.00,\"livelyDevCntCompare\":8.99,\"livelyDevCnt\":1527,\"onlineDevRate\":23.08,\"crtDevCnt\":169025,\"livelyDevRate\":51.90,\"crtDevCntCompare\":0.08,\"onlineDevCnt\":679,\"actDevRate\":1.74,\"actDevCntCompare\":4.55}]"
            },
            "requestId": "6B78B8DB-EBDB-4451-BE30-893714******",
            "success": true
        },
        "headers": {
            "access-control-allow-origin": "*",
            "date": "Mon, 15 Mar 2021 07:24:01 GMT",
            "content-length": "425",
            "access-control-max-age": "172800",
            "x-acs-request-id": "6B78B8DB-EBDB-4451-BE30-893714******",
            "access-control-allow-headers": "X-Requested-With, X-Sequence, _aop_secret, _aop_signature",
            "connection": "keep-alive",
            "content-type": "application/json;charset=utf-8",
            "access-control-allow-methods": "POST, GET, OPTIONS"
        }
    }
  • Failure: Use the error code in the response to identify the cause. For more information about error codes, see Error codes.

    The following example shows a failed response. The parameter __instance_idd__ is invalid. Correct it to __instance_id__ and retry the API call.

    Exception in thread "main" com.aliyun.tea.TeaException: code: 400, invalid parameter:redundant query param : __instance_idd__ request id: 829096F...
    	at com.aliyun.teaopenapi.Client.doRPCRequest(Client.java:187)
    	at com.aliyun.iot20180120.Client.listAnalyticsDataWithOptions(Client.java:1636)
    	at com.aliyun.iot20180120.Client.listAnalyticsData(Client.java:1641)
    	at javademo.main(javademo.java:67)