当前位置: 首页 > news >正文

.net对接阿里云CSB服务

public Response<string> Main(MonthPlanRequest request){string apiName = "MonthPlan", postData =   request.ToJson(); var result = ConnectCSB(apiName, postData);return InvokeResult.Fail<string>("访问成功");}
	/// <summary>/// 请求方式post,参数为json格式/// </summary>/// <param name="apiName">api名称</param>/// <param name="postData">发送的参数</param>/// <returns></returns>public static string ConnectCSB(string apiName, string postData){var resultStr = "";try{string ACCESS_KEY = System.Configuration.ConfigurationManager.AppSettings["ACCESS_KEY"].ToString();string SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString();string CSBURL = System.Configuration.ConfigurationManager.AppSettings["CSBURL"].ToString();//签名时间戳long timeStamp = ToUnixTimeMilliseconds(DateTime.Now);//form表单提交的签名串生成示例string signature = sign(apiName, "1.0.0", timeStamp, ACCESS_KEY, SECRET_KEY, null, postData);Dictionary<string, string> headerDic = new Dictionary<string, string>();headerDic.Add("_api_access_key", ACCESS_KEY);//访问密钥headerDic.Add("_api_timestamp", timeStamp.ToString());//签名时间戳headerDic.Add("_api_name", apiName);  //需要调用的api名称headerDic.Add("_api_signature", signature);//签名headerDic.Add("_api_version", "1.0.0");//版本																	resultStr = GetResult(CSBURL, "application/json", "application/json;charset=utf-8", "POST", postData, headerDic);}catch (Exception e){ErpErrLog(e.Message, apiName);return "[{'IsSuccess': 'false','Msg':'" + e.Message + "'}]";}return resultStr;}
	public static long ToUnixTimeMilliseconds(DateTime nowTime){DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));// DateTime nowTime = DateTime.Now;long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);return unixTime;}
/// <summary>/// 本方法生成http请求的csb签名值。/// 调用csb服务时,需要在httpheader中增加以下几个头信息:/// _api_name: csb服务名/// _api_version: csb服务版本号/// _api_access_key: csb上的凭证ak/// _api_timestamp: 时间戳/// _api_signature: 本方法返回的签名串/// </summary>/// <param name="apiName">csb服务名</param>/// <param name="apiVersion">csb服务版本号</param>/// <param name="timeStamp">时间戳</param>/// <param name="accessKey">csb上的凭证ak</param>/// <param name="secretKey">csb上凭证的sk</param>/// <param name="formParamDict">form表单提交的参数列表(各参数值是还未urlEncoding编码的原始业务参数值)。如果是form提交,请使用 Content-Type= application/x-www-form-urlencoded </param>/// <param name="body">非form表单方式提交的请求内容,目前没有参与签名计算</param>/// <returns>签名串。</returns>public static string sign(string apiName, string apiVersion, long timeStamp, string accessKey, string secretKey, Dictionary<string, object[]> formParamDict, object body){Dictionary<string, object[]> newDict = new Dictionary<string, object[]>();if (formParamDict != null){foreach (KeyValuePair<string, object[]> pair in formParamDict){newDict.Add(pair.Key, pair.Value.Select(v => { return HttpUtility.UrlEncode(v.ToString()); }).ToArray());}}//设置csb要求的头参数newDict.Add("_api_name", new String[] { apiName });newDict.Add("_api_version", new String[] { apiVersion });newDict.Add("_api_access_key", new String[] { accessKey });newDict.Add("_api_timestamp", new object[] { timeStamp });//对所有参数进行排序var sortedDict = getSortByASCII(newDict);StringBuilder builder = new StringBuilder();foreach (KeyValuePair<string, object[]> pair in sortedDict){foreach (object obj in pair.Value){builder.Append(string.Format("{0}={1}&", pair.Key, obj));}}string str = builder.ToString();if (str.EndsWith("&")){str = str.Substring(0, str.Length - 1); //去掉最后一个多余的 & 符号}System.Security.Cryptography.HMACSHA1 hmacsha = new System.Security.Cryptography.HMACSHA1{Key = Encoding.UTF8.GetBytes(secretKey)};byte[] bytes = Encoding.UTF8.GetBytes(str);return Convert.ToBase64String(hmacsha.ComputeHash(bytes));}
public static string GetResult(string url, string accept, string contentType, string requestType, string parms, Dictionary<string, string> headerDic = null){var result = string.Empty;try{Stopwatch stopWatch = new Stopwatch();stopWatch.Start();var myRequest = (HttpWebRequest)WebRequest.Create(url);myRequest.Timeout = 300000;//100秒超时时间较短,需要调整成为300秒if (!string.IsNullOrEmpty(accept)){myRequest.Accept = accept;}if (!string.IsNullOrEmpty(contentType)){myRequest.ContentType = contentType;}//   myRequest.Headers.Add(new HttpRequestHeader(),"123");myRequest.Method = requestType;if (myRequest.Method == "POST"){var reqStream = myRequest.GetRequestStream();var encoding = Encoding.GetEncoding("utf-8");var inData = encoding.GetBytes(parms);reqStream.Write(inData, 0, inData.Length);reqStream.Close();}if (headerDic != null){foreach (var h in headerDic){myRequest.Headers.Add(h.Key, h.Value);}}//发送post请求到服务器并读取服务器返回信息    var res = (HttpWebResponse)myRequest.GetResponse();if (res.StatusCode != HttpStatusCode.OK) return result;var receiveStream = res.GetResponseStream();var encode = Encoding.GetEncoding("utf-8");if (receiveStream != null){var readStream = new StreamReader(receiveStream, encode);var oResponseMessage = readStream.ReadToEnd();res.Close();readStream.Close();result = oResponseMessage;ErpResult re = JsonConvert.DeserializeObject(result, typeof(ErpResult)) as ErpResult;if (re.code.Equals("000000")){ return "[{'IsSuccess': 'true','Msg':'" + re.message + "'}]";}elsereturn "[{'IsSuccess': 'false','Msg':'" + re.message + "'}]";}stopWatch.Stop();}catch (Exception e){ErpErrLog(e.Message, headerDic["_api_name"].ToString());if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError){WebResponse errResp = ((WebException)e).Response;using (Stream respStream = errResp.GetResponseStream()){var readStream = new StreamReader(respStream, Encoding.GetEncoding("utf-8"));var strError = readStream.ReadToEnd();Console.Out.WriteLine(strError);// read the error response}}return "[{'IsSuccess': 'false','Msg':'"+e.Message+"'}]";}return "[{'IsSuccess': 'true','Msg':'" + result + "'}]";}
public static Dictionary<string, object[]> getSortByASCII(Dictionary<string, object[]> dict){var sortList = dict.ToList();//经过测试以下三种是正确的,会按照ASCII码排序sortList.Sort((x, y) =>{return string.CompareOrdinal(x.Key, y.Key);});sortList.Sort((x, y) =>{var r = string.Compare(x.Key, y.Key, StringComparison.Ordinal);return r;});Dictionary<string, object[]> sortDict = new Dictionary<string, object[]>();var keys = dict.Keys.ToArray();Array.Sort(keys, string.CompareOrdinal); //anforeach (var key in keys){sortDict.Add(key, dict[key]);}return sortDict;}
http://www.lryc.cn/news/238628.html

相关文章:

  • Json数据格式
  • Kafka-Producer
  • Ubuntu20上离线安装samba
  • 【开源】基于Vue.js的教学过程管理系统
  • 【C++】泛型编程 ⑪ ( 类模板的运算符重载 - 函数实现 写在类外部的不同的 .h 头文件和 .cpp 代码中 )
  • 动手学深度学习——循环神经网络的简洁实现(代码详解)
  • 19.删除链表的倒数第 N 个节点
  • 机器人制作开源方案 | 莲花灯
  • 华为无线ac+fit三层组网,每个ap发射不同的业务vlan
  • 人工智能:科技之光,生活之美
  • mysql8.0英文OCP考试第61-70题
  • WaveletPool:抗混叠在微小目标检测中的重要性
  • 文章系列2:Unraveling the functional dark matter through global metagenomics
  • ubuntu 20.04 搭建crash dump问题分析环境
  • 算法训练营一刷 总结篇
  • Linux中的MFS分布式文件系统
  • 气相色谱质谱仪样品传输装置中电动针阀和微泄漏阀的解决方案
  • ArkTS基础知识
  • Kotlin学习(二)
  • LangChain 6根据图片生成推广文案HuggingFace中的image-caption模型
  • QFontDialog开发详解
  • 【C++进阶之路】第七篇:异常
  • shell 判断文件是否存在(csh bash)
  • 第六年到第十年是分水岭
  • 关于标准库中的string类 - c++
  • Chrome添加扩展程序
  • C++单调向量算法:132模式枚举1简洁版
  • 【ARFoundation学习笔记】2D图像检测跟踪
  • 计算机算法分析与设计(24)---分支限界章节复习
  • 二十三种设计模式-解密状态模式:优雅地管理对象状态