概述
第一步
获取华为云物联网平台的证书 (需要证书的可以留言)
第二个证书在华为oceanconnect上传()
本次测试c#端只需要第二个证书就可完成
首先我们看先看看它的api
应为我们只需要读取NB-IoT上报的数据所以只需要用到这个api
第二步
进入正题首先是封装sdk和josn
josn的封装
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
鉴权 获取toke
/// <summary>
/// 设备profile:data1 int data2 string(8,32) ret1 int ret2 string(8,32) para1 para2 para12 para22
/// 0xf0上报0xff命令相应0x91 cmd1 0x92 cmd2
/// </summary>
public class TokenResult
{
/// <summary>
/// 申请权限范围,即accessToken所能访问物联网平台资源的范围,参数值固定为default。
/// </summary>
public string scope { get; set; }
/// <summary>
/// accessToken的类型,参数值固定为Bearer 。
/// </summary>
public string tokenType { get; set; }
/// <summary>
/// accessToken的有效时间,参数值固定为3600秒
/// </summary>
public int expiresIn { get; set; }
/// <summary>
/// 鉴权参数,访问物联网平台API接口的凭证。
/// </summary>
public string accessToken { get; set; }
/// <summary>
/// 鉴权参数,有效时间为1个月,用于“刷新Token”接口。
/// 当accessToken即将过期时,可通过“刷新Token”接口来获取新的accessToken。
/// </summary>
public string refreshToken { get; set; }
}
获取设备历史数据
public class DeviceDataHistoryDTOsItem
{
/// <summary>
/// 获取设备ID,用于唯一标识一个设备,在注册设备时由物联网平台分配获得
/// </summary>
public string deviceId { get; set; }
/// <summary>
/// 获取网关ID,用于标识一个网关设备。当设备是直连设备时,gatewayId与设备的deviceId一致。当设备是非直连设备时,gatewayId为设备所关联的直连设备(即网关)的deviceId。
/// </summary>
public string gatewayId { get; set; }
/// <summary>
/// 获取设备所属的应用ID,当查询授权应用下设备的历史数据时才需要填写
/// </summary>
public string appId { get; set; }
/// <summary>
/// 获取设备的服务标识
/// </summary>
public string serviceId { get; set; }
/// <summary>
/// 获取设备上报的数据。
/// </summary>
public Dictionary<string, string> data { get; set; }
public string DataString
{
get
{
string result = "";
foreach (KeyValuePair<string, string> item in data)
{
result += item.Key + ":" + item.Value + "rn";
}
return result;
}
}
/// <summary>
///上报数据的UTC时间,时间格式:yyyyMMdd'T'HHmmss'Z',如20151212T121212Z。若需要显示本地时区时间,您需要自己进行时间转换。
/// </summary>
public string timestamp { get; set; }
}
public class HistoryDataResult
{
/// <summary>
/// 查询的记录数量。
/// </summary>
public int totalCount { get; set; }
/// <summary>
/// 查询的页码
/// </summary>
public int pageNo { get; set; }
/// <summary>
/// 查询每页信息的数量。
/// </summary>
public int pageSize { get; set; }
/// <summary>
/// 设备历史数据列表
/// </summary>
public List<DeviceDataHistoryDTOsItem> deviceDataHistoryDTOs { get; set; }
}
同理你也可以对其他api进行封装
sdk的封装
鉴权获取toke
//获取token
public TokenResult getToken()
{
TokenResult result = null;
string apiPath = "/iocm/app/sec/v1.1.0/login";
string body = "appId=" + this.m_appid + "&secret=" + this.m_appsecret;
string method = "POST";
string contenttype = "application/x-www-form-urlencoded";
WebHeaderCollection headers = new WebHeaderCollection();
try
{
ApiResult apiresult = PostUrl(apiPath, body, headers, method, contenttype, this.m_p12certfile, this.m_certpassword);
log(apiresult.statusCode.ToString() + apiresult.result);
TokenResult tr = JsonConvert.DeserializeObject<TokenResult>(apiresult.result);
result = tr;
}
catch (Exception ex)
{
log(ex.Message);
log(ex.StackTrace);
result = null;
}
return result;
}
查看历史数据
//查询历史数据
public HistoryDataResult queryHistoryData(string token, string deviceId, int count)
{
return queryHistoryData(token, deviceId, deviceId, "", "", 0, count, "", "");
}
public HistoryDataResult queryHistoryData(string token, string deviceId, string serviceid, int pageno, int pagesize, string starttime, string endtime)
{
return queryHistoryData(token, deviceId, deviceId, serviceid, "", pageno, pagesize, starttime, endtime);
}
//数据接收
public HistoryDataResult queryHistoryData(string token, string deviceId, string gatewayid, string serviceId, string property, int pageno, int pagesize, string starttime, string endtime)
{
HistoryDataResult result = null;
string apiPath = string.Format("/iocm/app/data/v1.2.0/deviceDataHistory?deviceId={0}&gatewayId={1}&serviceId={2}&pageNo={3}&pageSize={4}&startTime={5}&endTime={6}&property={7}&appId={8}", deviceId, gatewayid, serviceId, pageno, pagesize, starttime, endtime, property, this.m_appid);
string body = "";
string method = "GET";
string contenttype = "application/json";
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("app_key", this.m_appid);
headers.Add("Authorization", "Bearer " + token);
try
{
ApiResult apiresult = PostUrl(apiPath, body, headers, method, contenttype, this.m_p12certfile, this.m_certpassword);
log(apiresult.statusCode.ToString() + apiresult.result);
HistoryDataResult tr = JsonConvert.DeserializeObject<HistoryDataResult>(apiresult.result);
result = tr;
}
catch (Exception ex)
{
log(ex.Message);
log(ex.StackTrace);
result = null;
}
return result;
}
https请求
private void log(string msg)
{
File.AppendAllText(this.m_logfile, msg);
}
public class ApiResult
{
public int statusCode;
public string result;
public string errcode;
public string memo;
}
private ApiResult PostUrl(string apiPath, string postData, WebHeaderCollection headers, string method, string contenttype, string p12certfile, string cerpassword)
{
string url = string.Format("https://{0}:{1}{2}", this.m_pltip, this.m_pltPort, apiPath);
if (isHttp)
{
url = string.Format("http://{0}:{1}{2}", this.m_pltip, this.m_pltPort, apiPath);
}
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
X509Certificate2 cerCaiShang = new X509Certificate2(p12certfile, cerpassword);
if (!isHttp)
{
httpRequest.ClientCertificates.Add(cerCaiShang);
}
httpRequest.Method = method;
httpRequest.ContentType = contenttype;
httpRequest.Referer = null;
httpRequest.AllowAutoRedirect = true;
httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
httpRequest.Accept = "*/*";
for (int i = 0; i < headers.Count; i++)
{
for (int j = 0; j < headers.GetValues(i).Length; j++)
{
httpRequest.Headers.Add(headers.Keys[i], headers.GetValues(i)[j]);
}
}
if (isHttp) { httpRequest.ServicePoint.Expect100Continue = false; }
//
if (method != "GET")
{
Stream requestStem = httpRequest.GetRequestStream();
StreamWriter sw = new StreamWriter(requestStem);
sw.Write(postData);
sw.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream receiveStream = httpResponse.GetResponseStream();
string result = string.Empty;
using (StreamReader sr = new StreamReader(receiveStream))
{
result = sr.ReadToEnd();
}
ApiResult r = new ApiResult();
r.result = result;
r.statusCode = (int)httpResponse.StatusCode;
return r;
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return true;
}
同理你也可以对其他api进行封装 大体思路就是这样
最后
以上就是端庄自行车为你收集整理的c#通过HTTPS获取华为北向数据(一)——.NET的sdk和json封装的全部内容,希望文章能够帮你解决c#通过HTTPS获取华为北向数据(一)——.NET的sdk和json封装所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复