SDK使用说明及开发实例
更新时间:2018-10-13 13:03:42
概述
平台API按照阿里云API网关的调用方式,在调用参数中增加了request和params参数,参数示例如下:
{
id: UUID.v1(), //API网关 请求唯一标识,必填
version: '1.0', //API网关协议版本,固定值1.0
request: { //工业平台参数
iotToken:'token' , //工业平台参数 iottoken,选填
apiVer:'1.0.3' //工业平台api版本,必填
},
params: {
key1:'value1', //工业平台api的入参
key2:'value2' , //工业平台api的入参
}
}
公共参数
参数名称 | 类型 | 是否必须 | 默认值 | 参数描述 |
---|---|---|---|---|
AppKey | string | 是 | 无 | 账户的验证ID |
AppSecret | string | 是 | 无 | 账户的验证密码 |
AppKey以及AppSecret可以在账户验证信息管理中获取。其他参数请参考接口列表中的具体要求。
参数名称 | 类型 | 是否必须 | 默认值 | 参数描述 |
---|---|---|---|---|
Host | string | 是 | 无 | 服务域名 |
Path | string | 是 | 无 | API路径 |
目前平台提供的host地址如下,用户可以在API接口列表中的“查看详情”中查看host和path参数。
test.industry.chongqing.webhost.aliplus.com
c9506227f3bc4300a22d5ca0855c29e7-cn-shanghai.alicloudapi.com
调用示例
JAVA
将Maven坐标添加至项目的pom.xml文件
<dependency>
<groupId>com.aliyun.api.gateway</groupId>
<artifactId>sdk-core-java</artifactId>
<version>1.0.4</version>
</dependency>
SDK源码地址参考——github
-https://mvnrepository.com/artifact/com.aliyun.api.gateway/sdk-core-java/1.0.4
-https://github.com/aliyun/apigateway-sdk-core
示例代码
import com.alibaba.cloudapi.sdk.core.BaseApiClient;
import com.alibaba.cloudapi.sdk.core.enums.Method;
import com.alibaba.cloudapi.sdk.core.enums.Scheme;
import com.alibaba.cloudapi.sdk.core.http.ApacheHttpClient;
import com.alibaba.cloudapi.sdk.core.model.ApiRequest;
import com.alibaba.cloudapi.sdk.core.model.ApiResponse;
import com.alibaba.cloudapi.sdk.core.model.BuilderParams;
import com.alibaba.fastjson.JSONObject;
import java.io.UnsupportedEncodingException;
public class IIoTAPIGatewayDemo extends BaseApiClient {
public IIoTAPIGatewayDemo(BuilderParams builderParams) {
super(builderParams);
}
public static void main(String [] args) throws UnsupportedEncodingException {
BuilderParams clientParams = new BuilderParams();
clientParams.setAppKey("你的AppKey");
clientParams.setAppSecret("你的appSecret");
//1.获取client实例
IIoTAPIGatewayDemo client = new IIoTAPIGatewayDemo(clientParams);
//2.构造飞象平台开放API的Request结构体
ApiRequest request = buildRequest();
//3.发起工业开放API调用
ApiResponse response = client.syncInvoke(request);
System.out.println(response.getMessage());
System.out.println(new String(response.getBody()));
}
/**
* 构造请求body
*/
private static ApiRequest buildRequest() throws UnsupportedEncodingException {
String host = "test.industry.chongqing.webhost.aliplus.com";
String path = "api的path";
JSONObject request = new JSONObject();
request.put("apiVer","1.0.3");//api版本,必填
JSONObject params = new JSONObject();
params.put("key1","value1");// api入参
params.put("key2","value2");// api入参
JSONObject requestBody = new JSONObject();
requestBody.put("id",System.currentTimeMillis());//请求唯一标识,必填
requestBody.put("version","1.0");//协议版本,固定值1.0
requestBody.put("request",request);//请求唯一标识,必填
requestBody.put("params",params);//api入参结构体
System.out.println(requestBody.toJSONString());
byte[] body = requestBody.toJSONString().getBytes("UTF-8");
ApiRequest apiRequest = new ApiRequest(Scheme.HTTPS, Method.POST_BODY,
host,path,
body);
apiRequest.getHeaders().put("accept", "application/json");
return apiRequest;
}
}
//查询设备详情的完整例子
public class IIoTAPIGatewayDemo extends BaseApiClient {
public IIoTAPIGatewayDemo(BuilderParams builderParams) {
super(builderParams);
}
public static void main(String[] args) throws UnsupportedEncodingException {
BuilderParams clientParams = new BuilderParams();
clientParams.setAppKey("249153xx");
clientParams.setAppSecret("a7a53ed132c7be05f2e085xxxxx");
//1.获取client实例
IIoTAPIGatewayDemo client = new IIoTAPIGatewayDemo(clientParams);
//2.构造飞象平台开放API的Request结构体
ApiRequest request = buildRequest();
//3.发起工业开放API调用
ApiResponse response = client.syncInvoke(request);
System.out.println(response.getMessage());
System.out.println(new String(response.getBody()));
}
/**
* 构造请求body
*/
private static ApiRequest buildRequest() throws UnsupportedEncodingException {
String host = "test.industry.chongqing.webhost.aliplus.com";
String path = "/thing/device/detail/get";
JSONObject request = new JSONObject();
//api版本,必填
request.put("apiVer", "1.1.0");
JSONObject params = new JSONObject();
// api入参
params.put("productKey", "b1Q03Kb1Yyg");
// api入参
params.put("deviceName", "n7m1HbDdinIcXCYh0Gkz");
JSONObject requestBody = new JSONObject();
//请求唯一标识,必填
requestBody.put("id", System.currentTimeMillis());
//协议版本,固定值1.0
requestBody.put("version", "1.0");
//请求唯一标识,必填
requestBody.put("request", request);
//api入参结构体
requestBody.put("params", params);
System.out.println(requestBody.toJSONString());
byte[] body = requestBody.toJSONString().getBytes("UTF-8");
ApiRequest apiRequest = new ApiRequest(Scheme.HTTPS, Method.POST_BODY, host, path, body);
apiRequest.getHeaders().put("accept", "application/json");
return apiRequest;
}
}
Python
1.请至github仓库下载最新的SDK源码:https://github.com/aliyun/api-gateway-demo-sign-python
2.将SDK源码放到工程目录下,并在应用代码中进行相关的引用。
示例代码
# https://github.com/sunfuze/api-gateway-demo-sign-python
import uuid
import json
from com.aliyun.api.gateway.sdk import client
from com.aliyun.api.gateway.sdk.http import request
from com.aliyun.api.gateway.sdk.common import constant
#test.industry.chongqing.webhost.aliplus.com
host = "api域名"
url = "api的path"
cli = client.DefaultClient(app_key="你的<AppKey>", app_secret="你的<AppSecret>")
#post form
req_post = request.Request(host=host, protocol=constant.HTTPS, url=url, method="POST", time_out=30000)
bodyMap = {
'id': str(uuid.uuid4()),
#必选,协议版本,固定值1.0
'version': "1.0",
'request': {
#可选
'iotToken': "xxxx",
#必选,api的版本
'apiVer': "1.0.3"
},
'params': {
#接口参数
'key1':"value1"
}
}
headers = {
'accept': 'application/json'
}
req_post.set_body(bodyMap)
req_post.set_headers(headers)
req_post.set_content_type(constant.CONTENT_TYPE_JSON)
print cli.execute(req_post)
Dot NET
1.请到github仓库下载最新的SDK及Demo:https://github.com/aliyun/api-gateway-demo-sign-net/
2.将SDK包添加至项目文件夹下,并在应用中引用SDK。
示例代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using aliyun_api_gateway_sdk.Constant;
using aliyun_api_gateway_sdk.Util;
namespace aliyun_api_gateway_sdk
{
public class Valiadation
{
public Valiadation()
{
}
static void Main(string[] args)
{
String appkey = "249176xx";
String appSecret = "18034e6db58935809929ad22b1c378xx";
//String bobyContent = "{\"request\": {\"apiVer\": \"1.0.3\"},\"id\": 1508345655455,\"params\":
{\"authInfo\":\"value1\"},\"version\": \"1.0\"}";
//String path = "/app/aepauth/handle";
String bobyContent = "{\"request\": {\"apiVer\": \"1.0.3\"},\"id\": 1508345655455,\"params\":
{\"productKey\":\"b1Xg0SyLR34\",\"deviceName\":\"eqT2KpwXLfxrjWt4hlk4\",\"ruleType\":\"ONS\"},\"version\": \"1.0\"}";
String path = "/industry/ruleAction/query";
String host = "test.industry.chongqing.webhost.aliplus.com";
Dictionary<String, String> headers = new Dictionary<string, string>();
Dictionary<String, String> querys = new Dictionary<string, string>();
Dictionary<String, String> bodys = new Dictionary<string, string>();
List<String> signHeader = new List<String>();
//设定Content-Type,根据服务器端接受的值来设置¸
headers.Add(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_STREAM);
//设定Accept,根据服务器端接受的值来设置
headers.Add(HttpHeader.HTTP_HEADER_ACCEPT, ContentType.CONTENT_TYPE_JSON);
//注意:如果有非Form形式数据(body中只有value,没有key);如果body中是key/value形式数据,不要指定此行
headers.Add(HttpHeader.HTTP_HEADER_CONTENT_MD5,
MessageDigestUtil.Base64AndMD5(Encoding.UTF8.GetBytes(bobyContent)));
//注意:业务body部分
bodys.Add("", bobyContent);
//指定参与签名的header
signHeader.Add(SystemHeader.X_CA_TIMESTAMP);
using (HttpWebResponse response = HttpUtil.HttpPost(host, path, appkey, appSecret, 30000, headers, querys, bodys, signHeader))
{
Stream st = response.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
// 通过reader.ReadToEnd获取返回结果,正常情况下结果是一个json string
Console.WriteLine(reader.ReadToEnd());
}
Console.Read();
}
}
}
NODE
安装SDK
sudo npm install aliyun-api-gateway
SDK npm下载地址:https://www.npmjs.com/package/aliyun-api-gateway
SDK github地址:https://github.com/aliyun/api-gateway-nodejs-sdk
添加依赖
"dependencies": {
"aliyun-api-gateway": "1.1.4"
},
示例代码
'use strict';
const co = require('co');
const UUID = require('uuid');
const Client = require('aliyun-api-gateway').Client;
//app的AppKey,appSecret
const client = new Client('APP_KEY','APP_SECRET');
co(function* () {
//test.industry.chongqing.webhost.aliplus.com
var url = 'API域名'+'API Path';
var result = yield client.post(url, {
data: {
id: UUID.v1(), // 请求唯一标识,必填
version: '1.0', // 协议版本,固定值1.0
request: {
iotToken:'token' , // iottoken,选填
apiVer:'1.0.3' // api版本,必填
},
params: {
key1:'value1', //api的入参
key2:'value2' , //api的入参
}
},
headers: {
accept: 'application/json'
}
});
console.log(JSON.stringify(result));
});
PHP
SDK下载
请到github仓库下载最新的SDK及Demo:https://github.com/aliyun/api-gateway-demo-sign-php
将SDK包添加至项目文件夹下。并在应用中引用SDK
示例代码
以publish数据到设备为例。
$request = new Iot\PubRequest();
$request->setProductKey("productKey");
$request->setMessageContent("aGVsbG93b3JsZA="); //hello world Base64 String.
$request->setTopicFullName("/productKey/deviceName/get"); //消息发送到的Topic全名.
$response = $client->getAcsResponse($request);
print_r($response);