c# 调用带网关的API接口

long tmsp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds);
Dictionary<string, string> urlParams = new Dictionary<string, string>();
Dictionary<string, string> signParams = new Dictionary<string, string>();
Dictionary<string, string> bodyParams = new Dictionary<string, string>();
urlParams["api"] = "url";
urlParams["apiVersion"] = "1.0.0";
urlParams["timestamp"] = tmsp.ToString();

var inputbody = Newtonsoft.Json.JsonConvert.SerializeObject(batteryInfos);//数据值

bodyParams["batteryInfoList"] = inputbody;

urlParams.ToList().ForEach(x =>
{
   signParams.Add(x.Key, x.Value);
});

bodyParams.ToList().ForEach(x =>
{
    signParams.Add(x.Key, x.Value);
});

StringBuilder sb = new StringBuilder();
sb.Append("key");//key
signParams.OrderBy(x => x.Key, StringComparer.Ordinal).ToList()
.ForEach(entry =>
{
 sb.Append(entry.Key);
 sb.Append(entry.Value);
});
sb.Append("key");

var sign = PhihamNet.Core.Comm.Common.GetMd5(sb.ToString());
StringBuilder url = new StringBuilder();
url.Append("url");//
urlParams.OrderBy(x => x.Key, StringComparer.Ordinal).ToList().ForEach(entry =>
{
  url.Append(entry.Key);
  url.Append("=");
  url.Append(entry.Value);
  url.Append("&");
});

url.Append("sign");
url.Append("=");
url.Append(sign);

var webRequest = WebRequest.Create(url.ToString());
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = "POST";
webRequest.Timeout = int.MaxValue;

 using (Stream requestStream = webRequest.GetRequestStream())
{
        var inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(bodyParams);
         byte[] paramBytes = Encoding.UTF8.GetBytes(inputJson);
         requestStream.Write(paramBytes, 0, paramBytes.Length);
}

WebResponse webResponse = webRequest.GetResponse();

HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;

var Statuscode = string.Empty;
if (httpWebResponse != null)
{
       Statuscode += (int)httpWebResponse.StatusCode;
       Statuscode += " : ";
       Statuscode += httpWebResponse.StatusDescription;
       Statuscode += "  \r\n ";

}

 using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
      StringBuilder osb = new StringBuilder();
       var result = streamReader.ReadToEnd();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值