InvokeRestCenter.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using Newtonsoft.Json.Linq;
  2. using PTMedicalInsurance.Common;
  3. using PTMedicalInsurance.Variables;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. using System.Data;
  14. namespace PTMedicalInsurance.Helper
  15. {
  16. class InvokeRestCenter : IInvokeCenter
  17. {
  18. private static string GetRandomString(int length)
  19. {
  20. const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  21. var random = new Random();
  22. return new string(Enumerable.Repeat(chars, length)
  23. .Select(s => s[random.Next(s.Length)]).ToArray());
  24. }
  25. private static long GetCurrentUnixSeconds()
  26. {
  27. DateTimeOffset utcNow = DateTimeOffset.UtcNow.AddHours(8);
  28. return (long)(utcNow.ToUniversalTime().DateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalSeconds;
  29. }
  30. private static string GetSHA256Str(string input)
  31. {
  32. using (SHA256 sha256Hash = SHA256.Create())
  33. {
  34. byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  35. StringBuilder builder = new StringBuilder();
  36. foreach (byte b in bytes)
  37. {
  38. builder.Append(b.ToString("x2"));
  39. }
  40. return builder.ToString();
  41. }
  42. }
  43. public int Business(string inputData, ref string outputData)
  44. {
  45. outputData = "";
  46. JObject joRtn = new JObject();
  47. try
  48. {
  49. string _api_timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
  50. string _api_name = Global.inf.apiName;
  51. string _api_version = "1.0.0";
  52. string _api_access_key = Global.inf.AK;
  53. string secretKey = Global.inf.SK;
  54. //签名
  55. string sTemp = "_api_access_key=" + _api_access_key + "&_api_name=" + _api_name + "&_api_timestamp=" + _api_timestamp + "&_api_version=" + _api_version;
  56. string _api_signature = Encrypt.ToBase64hmac(sTemp, secretKey);
  57. Global.writeLog($"_api_timestamp:{_api_timestamp}\n_api_name:{_api_name}\n_api_version:{"1.0.0"}" +
  58. $"\n_api_access_key:{_api_access_key}\nsecretKey:{secretKey}\n_api_signature:{_api_signature}" +
  59. $"\nurl:{Global.curEvt.URL}");
  60. //创建一个HTTP请求
  61. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
  62. //Post请求方式
  63. request.Method = "POST";
  64. //内容类型
  65. request.ContentType = "application/json";
  66. //增加头部信息
  67. request.Headers.Add("_api_timestamp", _api_timestamp);
  68. request.Headers.Add("_api_name", _api_name);
  69. request.Headers.Add("_api_version", _api_version);
  70. request.Headers.Add("_api_access_key", _api_access_key);
  71. request.Headers.Add("_api_signature", _api_signature);
  72. //设置参数,并进行URL编码
  73. string paraUrlCoded = inputData;
  74. byte[] payload;
  75. //将Json字符串转化为字节
  76. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  77. //设置请求的ContentLength
  78. request.ContentLength = payload.Length;
  79. //发送请求,获得请求流
  80. Stream writer;
  81. writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
  82. //将请求参数写入流
  83. writer.Write(payload, 0, payload.Length);
  84. writer.Close();//关闭请求流
  85. HttpWebResponse response = null;
  86. try
  87. {
  88. //获得响应流
  89. response = (HttpWebResponse)request.GetResponse();
  90. }
  91. catch (WebException ex)
  92. {
  93. HttpWebResponse res = (HttpWebResponse)ex.Response;
  94. Stream myResponseStream = res.GetResponseStream();
  95. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  96. string retString = myStreamReader.ReadToEnd();
  97. outputData = JsonHelper.setExceptionJson(-99, "异常返回", retString).ToString();
  98. return -1;
  99. }
  100. outputData = getResponseData(response);
  101. joRtn = JObject.Parse(outputData);//返回Json数据
  102. return 0;
  103. }
  104. catch (Exception ex)
  105. {
  106. joRtn.Add("infcode", -1);
  107. joRtn.Add("err_msg", "调用中心服务异常invokeCenterService(1):" + ex.Message);
  108. outputData = JsonHelper.toJsonString(joRtn);
  109. return -1;
  110. }
  111. }
  112. public int BusinessExt(string inputData, ref string outputData)
  113. {
  114. return this.Business(inputData, ref outputData);
  115. }
  116. public int DownloadFile(string inputData, ref string outputData)
  117. {
  118. outputData = "";
  119. string error = string.Empty; int errorCode = 0;
  120. try
  121. {
  122. JObject jsonInParam = JObject.Parse(inputData);
  123. // 去除外wrapper层便于通用
  124. Utils.removeWrapper(jsonInParam);
  125. string fileName = (string)jsonInParam["input"]["fsDownloadIn"]["filename"];
  126. string filePath = Global.curEvt.path + "\\Download\\" + fileName;
  127. //如果不存在目录,则创建目录
  128. if (!Directory.Exists(Global.curEvt.path + "\\Download"))
  129. {
  130. //创建文件夹
  131. DirectoryInfo dirInfo = Directory.CreateDirectory(Global.curEvt.path + "\\Download");
  132. }
  133. if (File.Exists(filePath))
  134. {
  135. File.Delete(filePath);
  136. }
  137. FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
  138. //创建一个HTTP请求
  139. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
  140. //Post请求方式
  141. request.Method = "POST";
  142. //内容类型
  143. request.ContentType = "application/json";
  144. string timestamp = TimeStamp.get13().ToString(); //当前时间戳(秒)
  145. string name = Global.inf.apiName;
  146. string version = "1.0.0";
  147. string access_key = Global.inf.AK;
  148. string secretKey = Global.inf.SK;
  149. //签名
  150. string sTemp = "_api_access_key=" + access_key + "&_api_name=" + name + "&_api_timestamp=" + timestamp + "&_api_version=" + version;
  151. string signature = Encrypt.ToBase64hmac(sTemp, Global.inf.SK);
  152. Global.writeLog($"_api_timestamp:{timestamp}\n_api_name:{Global.inf.apiName}\n_api_version:{"1.0.0"}\n_api_access_key:{Global.inf.AK}\n_api_signature:{signature}\nurl:{Global.curEvt.URL}");
  153. //增加头部信息
  154. request.Headers.Add("_api_timestamp", timestamp);
  155. request.Headers.Add("_api_name", Global.inf.apiName);
  156. request.Headers.Add("_api_version", "1.0.0");
  157. request.Headers.Add("_api_access_key", Global.inf.AK);
  158. request.Headers.Add("_api_signature", signature);
  159. //设置参数,并进行URL编码
  160. string paraUrlCoded = JsonHelper.toJsonString(jsonInParam);
  161. byte[] payload;
  162. //将Json字符串转化为字节
  163. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  164. //设置请求的ContentLength
  165. request.ContentLength = payload.Length;
  166. Stream writer;
  167. try
  168. {
  169. writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
  170. }
  171. catch (Exception)
  172. {
  173. writer = null;
  174. errorCode = -100;
  175. error = "连接服务器失败!";
  176. }
  177. //将请求参数写入流
  178. writer.Write(payload, 0, payload.Length);
  179. writer.Close();//关闭请求流
  180. // String strValue = "";//strValue为http响应所返回的字符流
  181. //发送请求并获取相应回应数据
  182. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  183. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  184. Stream responseStream = response.GetResponseStream();
  185. //创建本地文件写入流
  186. byte[] bArr = new byte[102400];
  187. int iTotalSize = 0;
  188. int size = responseStream.Read(bArr, 0, (int)bArr.Length);
  189. while (size > 0)
  190. {
  191. iTotalSize += size;
  192. fs.Write(bArr, 0, size);
  193. size = responseStream.Read(bArr, 0, (int)bArr.Length);
  194. }
  195. fs.Close();
  196. responseStream.Close();
  197. dynamic joReturn = new JObject();
  198. joReturn.errorCode = errorCode;
  199. joReturn.errorMessage = error;
  200. joReturn.filePath = filePath;
  201. outputData = joReturn.ToString();
  202. }
  203. catch (Exception ex)
  204. {
  205. errorCode = -100;
  206. error = ex.Message;
  207. dynamic joReturn = new JObject();
  208. joReturn.errorCode = errorCode;
  209. joReturn.errorMessage = error;
  210. outputData = joReturn.ToString();
  211. return -1;
  212. }
  213. finally
  214. {
  215. Global.writeLog("DownloadCenterFile" + "(" + Global.curEvt.URL + ")", inputData, outputData);
  216. }
  217. return 0;
  218. }
  219. public int Init(ref string pErrMsg)
  220. {
  221. return 0;
  222. }
  223. public int UploadFile(string inputData, ref string outputData, ref string pErrMsg)
  224. {
  225. throw new NotImplementedException();
  226. }
  227. private string getResponseData(HttpWebResponse response)
  228. {
  229. string data = "";
  230. if (response != null)
  231. {
  232. Stream s = response.GetResponseStream();
  233. StreamReader sRead = new StreamReader(s,Encoding.GetEncoding("UTF-8"));
  234. data = sRead.ReadToEnd();
  235. sRead.Close();
  236. response.Close();
  237. }
  238. return data;
  239. }
  240. }
  241. }