The Java SDK provided by Alibaba Cloud simplifies the process of calling DataService Studio APIs, allowing for easy retrieval of specified data. You can integrate the SDK into your project using Maven dependencies or by downloading the installation package for local setup. This topic demonstrates how to use the Java SDK to call the API for preset metrics, including the method and an example.
Prerequisites
To call the preset metrics API, ensure that the product and device are created and that data backup is complete. For detailed instructions, see Preset Metrics API.
To call the product data API or customize a service API, ensure the corresponding API is created. For detailed instructions, see Product Data API and Customize Service API.
For additional information, see Management and Usage.
Install the SDK
Set up a Java development environment.
Download the environment from the official Java website and follow the provided instructions for installation.
Install the IoT Platform SDK for Java.
Acquire Maven software from the official Apache Maven website.
Incorporate the IoT Platform SDK for Java using the following Maven dependencies:
<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>
Initiate a request
Below is an example code snippet for invoking the historical device count statistics from the preset metrics API in DataService Studio. Modify the code as needed based on the parameter descriptions to call the desired API.
The maximum requests per second (QPS) for a single Alibaba Cloud account when calling the DataService Studio API is 100.
// Sample code for calling the DataService Studio API
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.aliyun.teaopenapi.models.Config;
public class JavaDemo {
/**
* Initialize the client with AccessKey ID and AccessKey Secret
* @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);
// Set your access domain name
config.setEndpoint("iot.cn-shanghai.aliyuncs.com");
return new Client(config);
}
public static void main(String[] args_) throws Exception {
// Provide your AccessKey ID and AccessKey Secret
Client client = JavaDemo.createClient("LTAI4FyDFmKN************", "WF3onkl8cq3cTyVW8n************"));
ListAnalyticsDataRequest request = new ListAnalyticsDataRequest();
// Specify your API Path
request.setApiPath("/iot-cn-npk1v******/system/query/hist_dev_cnt_stat");
// Indicate the instance ID where your API is located
request.setIotInstanceId("iot-cn-npk1v******");
// Set paging parameters: page number
request.setPageNum(1);
// Set paging parameters: page size
request.setPageSize(100);
List<ListAnalyticsDataRequest.ListAnalyticsDataRequestCondition> conditions = new ArrayList<>();
// Define your business-related request parameters. For Condition configuration, refer to the description below.
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);
// Execute the API call and capture the response
ListAnalyticsDataResponse listAnalyticsDataResponse = client.listAnalyticsData(request);
// Output the response
System.out.println(JSON.toJSONString(listAnalyticsDataResponse));
}
}
System request parameters:
Name
Type
Required
Example Value
Description
accessKeyId
String
Yes
LTAI4FyDFmKN************
To obtain the AccessKey ID and AccessKey Secret, log on to the IoT Platform console, hover over the account profile picture, and single click Accesskey Management.
NoteIf using a RAM user, attach the AliyunIOTFullAccess permission policy to enable IoT Platform resource management. Failure to do so may result in a failed connection to the IoT Platform. For the authorization method, refer to Grant RAM Users Access to IoT Platform.
accessKeySecret
String
Yes
WF3onkl8cq3cTyVW8n************
Endpoint
String
Yes
iot.cn-shanghai.aliyuncs.com
The Alibaba Cloud service API server address. Ensure the region matches that of the IoT Platform product.
In this example, the region is China (Shanghai) (cn-shanghai).
apiPath
String
Yes
/iot-cn-npk1v******/system/query/hist_dev_cnt_stat
The operation path for the API. In DataService Studio's API list, single click View next to the API to access its product page and find the API Path value. For more details, see Manage API.
iotInstanceId
String
Yes
iot-cn-npk1u******
The ID of the instance hosting the API.
pageNum
Integer
Conditional
1
The page number for pagination.
pageSize
Integer
Conditional
100
The number of entries per page, up to a maximum of 100.
Business-related request parameters:
Name
Type
Required
Description
Related Code
fieldName
String
Yes
The name of the parameter in the request.
condition.setFieldName("entityId");
operate
String
Yes
The operator used for the parameter. Options include:
=
for exact value match.BETWEEN
for a range of values.IN
for multiple possible values.!=
for exclusion of a specific value.
condition.setOperate("=");
value
String
No
The value to be matched for the parameter.
ImportantThis parameter is necessary unless the operator is
BETWEEN
.condition.setValue("all");
betweenStart
String
No
The start value for a range parameter.
ImportantRequired when the operator is
BETWEEN
.condition.setBetweenStart("0");
betweenEnd
String
No
The end value for a range parameter.
ImportantRequired when the operator is
BETWEEN
.condition.setBetweenEnd("100");
Each request parameter is associated with a specific
condition
. To configure these conditions, refer to the API's product page where you can view and set the desired number ofcondition
. For guidance on accessing API request parameters, see Manage API.In the provided sample code, the API has three request parameters: __instance_id__, entityId, and statDate, which correspond to
condition
,condition1
, andcondition2
respectively.
Execution result
Success:
Detailed descriptions of the returned parameters can be found on the corresponding API's product page. For specific operations, see Management and Usage.
The example below illustrates the successful API response, which includes statistics on the number of devices for the public instance from February 21, 2021, to the time of the API call.
{ "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:
Understanding the reason for failure is possible by examining the error code in the result.
The example below shows a failed API call due to an invalid request parameter,
__instance_idd__
. Correct it to__instance_id__
and retry the request.