云端 API 调用(C#)
云端开放 API 是标准 HTTP 接口,C# 下用 HttpClient 直接调用,不依赖第三方库。
1. 鉴权头
每次请求带上两个头,值来自平台「项目秘钥」页:
var http = new HttpClient { BaseAddress = new Uri("https://iot.yfios.net/api/") };
http.DefaultRequestHeaders.Add("accessKeyId", accessKeyId);
http.DefaultRequestHeaders.Add("signature", accessKeySecret);
秘钥只绑定项目,调用时 projectId 必须在绑定范围内。
2. 统一响应
public class ApiResponse<T>
{
public int Code { get; set; }
public string Message { get; set; }
public string RequestId { get; set; }
public T Data { get; set; }
}
Code == 200 表示成功;其余情况 Message 给出失败原因。
3. 调用示例
using System.Net.Http;
using System.Text.Json;
var json = await http.GetStringAsync(
"device/QueryDeviceList?projectId=100001¤tPage=1&pageSize=20");
var resp = JsonSerializer.Deserialize<ApiResponse<DevicePage>>(json,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (resp.Code != 200) throw new Exception(resp.Message);
foreach (var d in resp.Data.List) Console.WriteLine(d.DeviceName);
服务调用(同步,等待设备响应)用 POST + JSON:
var body = JsonSerializer.Serialize(new {
iotId = "xxx",
serviceType = "restart",
inParameter = "{}"
});
var content = new StringContent(body, System.Text.Encoding.UTF8, "application/json");
var result = await http.PostAsync("property/InvokeDeviceService", content);
SetDeviceProperty(属性下发)是异步的,接口返回成功只表示指令已发出,设备执行结果体现在后续属性上报中。