IoT Platform SDK for Java allows you to use Java programs to manage IoT Platform resources with high efficiency. You can add the SDK as a dependency to your Maven project. You can also download the installation package to an on-premises directory to install the SDK.
Install the SDK
Install a Java development environment.
Download a Java installation package from the official Java website and install Java as prompted. We recommend that you install Java 8 or later.
Install IoT Platform SDK for Java.
Download a Maven installation package from the official Apache Maven website.
Add the following dependencies to your Maven project.
The dependency for IoT Platform SDK for Java of the latest version:
<!-- https://mvnrepository.com/artifact/com.aliyun/iot20180120 --> <dependency> <groupId>com.aliyun</groupId> <artifactId>iot20180120</artifactId> <version>3.0.8</version> </dependency>
The dependency for Alibaba Cloud SDK for Java:
<dependency> <groupId>com.aliyun</groupId> <artifactId>tea-openapi</artifactId> <version>0.2.2</version> </dependency>
For more information about the source code of the SDK for Java, see alibabacloud-java-sdk.
Initialize the SDK
Create the config object to store SDK initialization information, such as the AccessKey ID, AccessKey secret, and region ID.
Create the client instance and call the
com.aliyun.iot20180120.Client(config)
method to load the SDK information from config. The SDK is then initialized.The Request and Response parameters for subsequent API calls are obtained from
com.aliyun.iot 20180120.models
.
For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.
Config config = new Config();
// The AccessKey ID of your Alibaba Cloud account.
config.accessKeyId = "<your accessKey>";
// The AccessKey secret of your Alibaba Cloud account.
config.accessKeySecret = "<your accessSecret>";
// The ID of the region.
config.regionId = "cn-shanghai";
// Initialize the SDK.
Client client = new com.aliyun.iot20180120.Client(config);
Parameter | Description |
accessKeyId | The AccessKey ID of your Alibaba Cloud account. You can go to the AccessKey Pair page in the Alibaba Cloud Management Console to create or view your AccessKey pairs. |
accessKeySecret | The AccessKey secret of your Alibaba Cloud account. |
regionId | The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format. You can view the region in the upper-left corner of the IoT Platform console. For more information about the formats of region IDs, see Supported regions. |
Initiate a request
The SDK encapsulates two classes for each API operation. The class whose name is in the ${API name}+"Request"
format indicates the request, and the class whose name is in the ${API name}+"Response"
format indicates the response.
Procedure
Initialize the SDK. For more information, see Initialize the SDK.
Create an API request by generating a request instance of the
${API name}+"Request"
class.Call the
set+${Request parameter}
method of the request instance to specify the request parameters.Create a response instance of the
${API name}+"Response"
class to obtain the response: call the${API name}(request)
method of the client instance to obtain the response to the API request. The response includes the body and headers returned by the server.Use the body object of the response instance and call the
get+${Response parameter}
method to obtain the values of the response parameters.For example, the
response.getBody.getSuccess()
method is called to obtain the value of the Success parameter. This parameter is a common response parameter, which indicates whether the call is successful. Common response parameters also include RequestId, ErrorMessage, and Code.Call the
catch()
method to handle exceptions.
For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.
The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.
In the following sample code, ${iotInstanceId}
specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.
If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.
If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string (
""
) for the parameter. Otherwise, the call fails.
For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.
PubRequest request = new PubRequest()
.setIotInstanceId("${iotInstanceId}")
.setProductKey("${productKey}")
.setMessageContent(Base64.getEncoder().encodeToString("hello world".getBytes()))
.setTopicFullName("/${productKey}/${deviceName}/user/get")
.setQos(0); // QoS0 and QoS1 are supported.
try {
PubResponse response = client.pub(request);
// The response that contains the body and the headers that are returned by the server.
// Obtain the ID of the request.
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()) {
// Obtain the ID of a message that is sent from IoT Platform.
System.out.println(response.getBody().getMessageId());
// The else statement.
} else {
// The call fails.
// Obtain the error code.
System.out.println(response.getBody().getCode());
// Obtain the error description.
System.out.println(response.getBody().getErrorMessage());
}
} catch (TeaException error) {
// Exceptions that occur on the server.
System.out.println(error.getCode());
System.out.println(error.getMessage());
} catch (Exception e) {
// Other runtime exceptions.
e.printStackTrace();
}
Sample code
You can replace the values of the preceding parameters with actual values based on your business scenario.
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 {
/**
* Use your AccessKey ID and AccessKey secret to initialize the client.
*/
private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config();
config.accessKeyId = accessKeyId;
config.accessKeySecret = accessKeySecret;
// The ID of the region.
config.regionId = "cn-shanghai";
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);// QoS0 and QoS1 are supported.
PubResponse response = client.pub(request);
// Obtain the ID of the request.
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()) {
// Obtain the ID of a message that is sent from IoT Platform.
System.out.println(response.getBody().getMessageId());
// The else statement.
} else {
// The call fails.
// Obtain the error code.
System.out.println(response.getBody().getCode());
// Obtain the error description.
System.out.println(response.getBody().getErrorMessage());
}
} catch (TeaException error) {
// Exceptions that occur on the server.
System.out.println(error.getCode());
System.out.println(error.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Appendix: Sample code
You can view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.
Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.