1、 云端API介绍以及调试方法
https://help.aliyun.com/document_detail/69893.html?spm=a2c4g.11186623.6.749.1def3112gGOTHP
使用云端API之前务必先使用OpenAPI Explorer在线调试工具先调试通过。
https://api.aliyun.com/?spm=
a2c4g.11186623.2.12.240a3d29r9yc1o#/?product=Iot&version=2018-01-20&api=CreateProduct&tab=DEMO&lang=JAVA
其实我们的代码也就是从旁边的示例代码中搬运过来的。
2、使用common SDK调用云端API
前边已经说过,使用OpenAPI Explorer在线调试工具调试好之后,然后将示例代码放到自己的工程中
以创建产品为例:
调试通过,然后就可以放心把代码搬出来了
可以看到控制台上已经有新产品了。
编写代码
测试结果:
控制台上也新建了产品
源码:
pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.example</groupId>
- <artifactId>CallAPI</artifactId>
- <version>1.0-SNAPSHOT</version>
- <dependencies>
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-core</artifactId>
- <version>4.5.3</version>
- </dependency>
- </dependencies>
- </project>
CallAPI.Java
- package com.alibaba;
- import com.aliyuncs.CommonRequest;
- import com.aliyuncs.CommonResponse;
- import com.aliyuncs.DefaultAcsClient;
- import com.aliyuncs.IAcsClient;
- import com.aliyuncs.exceptions.ClientException;
- import com.aliyuncs.exceptions.ServerException;
- import com.aliyuncs.http.MethodType;
- import com.aliyuncs.profile.DefaultProfile;
- /*
- pom.xml
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-core</artifactId>
- <version>4.5.3</version>
- </dependency>
- */
- public class CallAPI {
- public static void main(String[] args) {
- DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI4*******vJdtXvT3G", "Mp2f4q*****9ud7rOPGl");
- IAcsClient client = new DefaultAcsClient(profile);
- CommonRequest request = new CommonRequest();
- request.setSysMethod(MethodType.POST);
- request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
- request.setSysVersion("2018-01-20");
- request.setSysAction("CreateProduct");
- request.putQueryParameter("RegionId", "cn-shanghai");
- request.putQueryParameter("NodeType", "0");
- request.putQueryParameter("ProductName", "ProductAPITestDemo6");
- request.putQueryParameter("DataFormat", "1");
- request.putQueryParameter("Description", "测试云端API用");
- request.putQueryParameter("AliyunCommodityCode", "iothub_senior");
- request.putQueryParameter("AuthType", "secret");
- try {
- CommonResponse response = client.getCommonResponse(request);
- System.out.println(response.getData());
- } catch (ServerException e) {
- e.printStackTrace();
- } catch (ClientException e) {
- e.printStackTrace();
- }
- }
- }
到官网下载Demo
点击链接后,进入Github(没有账户就注册一个)
导入到工程中
同样以创建产品为例,和common SDK一样要找到我们需要修改的参数AK SK等
发现调用到了ProductManager
继续追踪
测试结果:
控制台上创建新产品成功
源码直接去官网下载。
原文:
https://developer.aliyun.com/article/779727?spm=5176.8068049.0.0.55746d19QQJ9oF&groupCode=iot