HttpCommand.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Net;
  7. using System.IO;
  8. //using System.Web.Script.Serialization;
  9. using System.Web.Script.Serialization;
  10. using System.Web;
  11. namespace UAS_LabelMachine.PublicMethod
  12. {
  13. public class HttpCommand
  14. {
  15. /// <summary>
  16. /// 获取签名值
  17. /// </summary>
  18. /// <param name="parameters"></param>
  19. /// <param name="url"></param>
  20. /// <param name="secret"></param>
  21. /// <returns></returns>
  22. public static string Sign(IDictionary<string, string> parameters, string url, string secret)
  23. {
  24. var builder = new StringBuilder();
  25. builder.Append(url);
  26. builder.Append("\n");
  27. foreach (var param in parameters.OrderBy(t => t.Key))
  28. {
  29. builder.Append(string.Format("{0}={1}\n", param.Key, param.Value));
  30. }
  31. builder.Append(secret);
  32. return GetMd5(builder.ToString());
  33. }
  34. //获取MD5值
  35. public static string GetMd5(string src)
  36. {
  37. var buffer = new StringBuilder();
  38. using (var md5 = MD5.Create())
  39. {
  40. var md5Bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(src));
  41. for (var i = 0; i < md5Bytes.Length; i++)
  42. {
  43. var val = Convert.ToInt32(md5Bytes[i] & 0xff);
  44. if (val < 16)
  45. {
  46. buffer.Append("0");
  47. }
  48. buffer.Append(string.Format("{0:X}", val));
  49. }
  50. }
  51. return buffer.ToString();
  52. }
  53. /// <summary>
  54. /// 获取ESB的时间戳,即C#实现java这个方法System.currentTimeMillis(),产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数
  55. /// </summary>
  56. /// <param name="time"></param>
  57. /// <returns></returns>
  58. public static string ConvertTimeStamp(string time)
  59. {
  60. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  61. DateTime dtNow = DateTime.Parse(time);
  62. TimeSpan toNow = dtNow.Subtract(dtStart);
  63. string timeStamp = toNow.Ticks.ToString();
  64. timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
  65. return timeStamp;
  66. }
  67. /// <summary>
  68. /// 对 URL 字符串进行编码。
  69. /// </summary>
  70. /// <param name="dict"></param>
  71. /// <returns></returns>
  72. public static string buildEncodeUrl(IDictionary<string, string> dict)
  73. {
  74. StringBuilder sb = new StringBuilder();
  75. foreach (var param in dict.OrderBy(t => t.Key))
  76. {
  77. string encode = HttpUtility.UrlEncode(param.Value, Encoding.UTF8);
  78. sb.Append(param.Key).Append("=").Append(encode).Append("&");
  79. }
  80. return sb.ToString().Substring(0, sb.ToString().LastIndexOf("&"));
  81. }
  82. /// <summary>
  83. /// http方式获取数据
  84. /// </summary>
  85. /// <param name="url"></param>
  86. /// <param name="requestString"></param>
  87. /// <param name="method"></param>
  88. /// <param name="encoding"></param>
  89. /// <param name="times">请求超时时间(默认60秒)</param>
  90. /// <returns></returns>
  91. public static String GetResponseHTML(string url, string requestString, string method, Encoding encoding, int times = 60)
  92. {
  93. try
  94. {
  95. if (encoding == null)
  96. {
  97. encoding = Encoding.UTF8;
  98. }
  99. if (method == "POST")
  100. {
  101. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  102. req.Method = method;
  103. req.ContentType = "application/x-www-form-urlencoded";
  104. req.KeepAlive = false;
  105. req.Timeout = times * 1000;
  106. req.ReadWriteTimeout = times * 1000;
  107. //req.UserAgent = new HttpConfig().RMSUserAgent;
  108. //不需要根据http协议版本匹配,不需要进行协议握手就是说
  109. //Expect:100-Continue的作用是,设定Client 和 Server在Post数据前需要进行“请求头域”的数据匹配,相当于是握手。如果匹配则开始进行body 的内容,Post数据。否则,报错(417) Unkown
  110. req.ServicePoint.Expect100Continue = false;
  111. //传输请求的数据
  112. if (!string.IsNullOrEmpty(requestString))
  113. {
  114. byte[] data = encoding.GetBytes(requestString);
  115. req.ContentLength = data.Length;
  116. using (Stream stream = req.GetRequestStream())
  117. {
  118. stream.Write(data, 0, data.Length);
  119. //stream.Flush();
  120. stream.Close();
  121. }
  122. }
  123. //获取回传数据
  124. using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
  125. {
  126. StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
  127. string content = reader.ReadToEnd();
  128. reader.Close();
  129. return content;
  130. }
  131. }
  132. else
  133. {
  134. HttpWebRequest req = null;
  135. if (string.IsNullOrEmpty(requestString))
  136. {
  137. req = (HttpWebRequest)WebRequest.Create(url);
  138. }
  139. else if (url.IndexOf("?") > 0)
  140. {
  141. req = (HttpWebRequest)WebRequest.Create(url + "&" + requestString);
  142. }
  143. else
  144. {
  145. req = (HttpWebRequest)WebRequest.Create(url + "?" + requestString);
  146. }
  147. // req.Method = method;
  148. req.Timeout = times * 1000;
  149. req.ReadWriteTimeout = times * 1000;
  150. req.ServicePoint.Expect100Continue = false;
  151. req.ContentType = "application/x-www-form-urlencoded";
  152. //获取回传数据
  153. using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
  154. {
  155. StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
  156. string content = reader.ReadToEnd();
  157. reader.Close();
  158. return content;
  159. }
  160. }
  161. }
  162. catch (System.Net.WebException ex)
  163. {
  164. HttpWebResponse res = (HttpWebResponse)ex.Response;
  165. StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
  166. string errorMessage = sr.ReadToEnd();
  167. return errorMessage;
  168. }
  169. catch (Exception e)
  170. {
  171. //Logger log = new Logger();
  172. //log.LogException(e);
  173. return e.ToString();
  174. }
  175. }
  176. /// <summary>
  177. /// 检查UPN是否上传到OPPO成功
  178. /// </summary>
  179. /// <param name="esbUrl">OPPO的API URL</param>
  180. /// <param name="appId"></param>
  181. /// <param name="esbSecret"></param>
  182. /// <param name="upn">UPN条码</param>
  183. /// <returns>返回UPN的SN清单</returns>
  184. public String checkWmsBatteryInfo(string esbUrl, string appId, string esbSecret, string upn)
  185. {
  186. string uri = "/mes/extranet/check_wms_battery_info";
  187. Encoding encoding = Encoding.GetEncoding("utf-8");
  188. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  189. IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  190. StringBuilder builder = new StringBuilder();
  191. JavaScriptSerializer json = new JavaScriptSerializer();
  192. json.Serialize(sendData, builder);
  193. IDictionary<string, string> parameters = new Dictionary<string, string>();
  194. //parameters.Add("app_id", "SUP-FMT");
  195. parameters.Add("app_id", appId);
  196. parameters.Add("bat_upn", upn);
  197. parameters.Add("procstep", "1");
  198. parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  199. parameters.Add("sign", Sign(parameters, uri, esbSecret));
  200. string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), null, null);
  201. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  202. {
  203. return "Success";
  204. }
  205. else
  206. {
  207. return result;
  208. }
  209. }
  210. /// <summary>
  211. /// 插入电池信息到OPPO
  212. /// </summary>
  213. /// <param name="esbUrl"></param>
  214. /// <param name="appId"></param>
  215. /// <param name="esbSecret"></param>
  216. /// <param name="strBatteryList"></param>
  217. /// <returns>返回oppo插入的电池个数</returns>
  218. public String insertBatteryInfo(string esbUrl, string appId, string esbSecret, string strBatteryList)
  219. {
  220. //string uri = "/mes/basics/wms_battery_info_insert";
  221. string uri = "/mes/extranet/mes_test_result_info_insert";
  222. Encoding encoding = Encoding.GetEncoding("utf-8");
  223. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  224. //IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  225. //StringBuilder builder = new StringBuilder();
  226. //JavaScriptSerializer json = new JavaScriptSerializer();
  227. //json.Serialize(sendData, builder);
  228. IDictionary<string, string> parameters = new Dictionary<string, string>();
  229. //parameters.Add("app_id", "SUP-FMT");
  230. /*注意:参数添加到parameters,必须按参数字母顺序添加*/
  231. parameters.Add("app_id", appId);
  232. parameters.Add("test_info", strBatteryList);
  233. parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  234. parameters.Add("test_amount", "4");
  235. parameters.Add("sign", Sign(parameters, uri, esbSecret));
  236. string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null);
  237. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  238. {
  239. return "Success";
  240. }
  241. else
  242. {
  243. return result;
  244. }
  245. }
  246. public String insertUpnInfo(string esbUrl, string appId, string esbSecret, string strUpnlist, int count)
  247. {
  248. //string uri = "/mes/basics/wms_battery_info_insert";
  249. string uri = "/mes/extranet/mes_vendor_upn_inspection_result_insert";
  250. Encoding encoding = Encoding.GetEncoding("utf-8");
  251. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  252. IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  253. StringBuilder builder = new StringBuilder();
  254. JavaScriptSerializer json = new JavaScriptSerializer();
  255. json.Serialize(sendData, builder);
  256. IDictionary<string, string> parameters = new Dictionary<string, string>();
  257. //parameters.Add("app_id", "SUP-FMT");
  258. /*注意:参数添加到parameters,必须按参数字母顺序添加*/
  259. parameters.Add("app_id", appId);
  260. parameters.Add("inspection_amount", count.ToString());
  261. parameters.Add("inspection_info", strUpnlist);
  262. parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  263. parameters.Add("sign", Sign(parameters, uri, esbSecret));
  264. string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null);
  265. Console.WriteLine(result);
  266. //{"response":{"code":"200","success_count":2}}
  267. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  268. {
  269. return "Success";
  270. }
  271. else
  272. {
  273. return result;
  274. }
  275. }
  276. /// <summary>
  277. /// 删除UPN接口调用
  278. /// mes_vendor_upn_inspection_to_del_insert
  279. /// </summary>
  280. /// <param name="esbUrl"></param>
  281. /// <param name="appId"></param>
  282. /// <param name="esbSecret"></param>
  283. /// <param name="strUpnlist"></param>
  284. /// <returns></returns>
  285. public String deleteUpnInfo(string esbUrl, string appId, string esbSecret, string strUpnlist,int num)
  286. {
  287. //string uri = "/mes/basics/wms_battery_info_insert";
  288. string uri = "/mes/extranet/mes_vendor_upn_inspection_to_del_insert";
  289. Encoding encoding = Encoding.GetEncoding("utf-8");
  290. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  291. IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  292. StringBuilder builder = new StringBuilder();
  293. JavaScriptSerializer json = new JavaScriptSerializer();
  294. json.Serialize(sendData, builder);
  295. IDictionary<string, string> parameters = new Dictionary<string, string>();
  296. //parameters.Add("app_id", "SUP-FMT");
  297. /*注意:参数添加到parameters,必须按参数字母顺序添加*/
  298. //parameters.Add("app_id", appId);
  299. //parameters.Add("inspection_amount", "1");
  300. //parameters.Add("inspection_info", strUpnlist);
  301. //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  302. parameters.Add("app_id", appId);
  303. //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  304. parameters.Add("upn_amount", num.ToString());
  305. parameters.Add("upn_info", strUpnlist); //inspection_info test_info
  306. parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  307. parameters.Add("sign", Sign(parameters, uri, esbSecret));
  308. string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null);
  309. Console.Write(result);
  310. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  311. {
  312. return "Success";
  313. }
  314. else
  315. {
  316. return result;
  317. }
  318. }
  319. /// <summary>
  320. /// 获取UPN信息
  321. /// mes_vendor_upn_inspection_to_del_insert
  322. /// </summary>
  323. /// <param name="esbUrl"></param>
  324. /// <param name="appId"></param>
  325. /// <param name="esbSecret"></param>
  326. /// <param name="strUpnlist"></param>
  327. /// <returns></returns>
  328. public String getUpnInfo(string esbUrl, string appId, string esbSecret, string strUpn)
  329. {
  330. //string uri = "/mes/basics/wms_battery_info_insert";
  331. string uri = "/mes/extranet/mes_vendor_upn_process_result_list";
  332. Encoding encoding = Encoding.GetEncoding("utf-8");
  333. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  334. IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  335. StringBuilder builder = new StringBuilder();
  336. JavaScriptSerializer json = new JavaScriptSerializer();
  337. json.Serialize(sendData, builder);
  338. IDictionary<string, string> parameters = new Dictionary<string, string>();
  339. //parameters.Add("app_id", "SUP-FMT");
  340. /*注意:参数添加到parameters,必须按参数字母顺序添加*/
  341. //parameters.Add("app_id", appId);
  342. //parameters.Add("inspection_amount", "1");
  343. //parameters.Add("inspection_info", strUpnlist);
  344. //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  345. parameters.Add("app_id", appId);
  346. //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  347. // parameters.Add("upn_amount", "2");
  348. parameters.Add("upn_info", strUpn); //inspection_info test_info
  349. parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  350. parameters.Add("sign", Sign(parameters, uri, esbSecret));
  351. string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null);
  352. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  353. {
  354. return "Success";
  355. }
  356. else
  357. {
  358. return result;
  359. }
  360. }
  361. /// <summary>
  362. /// 获取锁卡信息接口调用
  363. /// mes_lock_card_info_list
  364. /// </summary>
  365. /// <param name="esbUrl"></param>
  366. /// <param name="appId"></param>
  367. /// <param name="esbSecret"></param>
  368. /// <returns></returns>
  369. public String Getinfo(string esbUrl, string appId, string esbSecret)
  370. {
  371. //string uri = "/mes/basics/wms_battery_info_insert";
  372. string uri = "/mes/extranet/mes_lock_card_info_list";
  373. Encoding encoding = Encoding.GetEncoding("utf-8");
  374. //Map<String, Object> sendData = new LinkedHashMap<String, Object>();
  375. IDictionary<string, Object> sendData = new Dictionary<string, Object>();
  376. StringBuilder builder = new StringBuilder();
  377. JavaScriptSerializer json = new JavaScriptSerializer();
  378. json.Serialize(sendData, builder);
  379. IDictionary<string, string> parameters = new Dictionary<string, string>();
  380. //parameters.Add("app_id", "SUP-FMT");
  381. /*注意:参数添加到parameters,必须按参数字母顺序添加*/
  382. //parameters.Add("app_id", appId);
  383. //parameters.Add("inspection_amount", "1");
  384. //parameters.Add("inspection_info", strUpnlist);
  385. //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
  386. parameters.Add("date_from", "20190227001000");
  387. parameters.Add("date_to", "20190228002000");
  388. parameters.Add("page_index", "1");
  389. parameters.Add("page_size", "10");
  390. parameters.Add("app_id", appId);
  391. // parameters.Add("upn_info", strUpnlist); //inspection_info test_info
  392. parameters.Add("timestamp", ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString());
  393. parameters.Add("sign", GetSign(parameters, uri.Trim(), esbSecret));
  394. string result = HttpGet(parameters, esbUrl + ":80" + uri, "GET");
  395. // string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "GET", null);
  396. if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result))
  397. {
  398. return "Success";
  399. }
  400. else
  401. {
  402. return result;
  403. }
  404. }
  405. public static string GetPostDataStr(IDictionary<string, string> dict)
  406. {
  407. string postDataStr = "";
  408. StringBuilder myStringBuilder = new StringBuilder();
  409. foreach (var item in dict)
  410. {
  411. myStringBuilder.Append(HttpUtility.UrlEncode(item.Key));
  412. myStringBuilder.Append("=");
  413. myStringBuilder.Append(HttpUtility.UrlEncode(item.Value));
  414. myStringBuilder.Append("&");
  415. }
  416. int lenght = myStringBuilder.ToString().Length;
  417. postDataStr = lenght > 1 ? myStringBuilder.ToString().Remove(lenght - 1) : "";
  418. return postDataStr;
  419. }
  420. public static string HttpGet(IDictionary<string, string> dict, string apiUrl, string strMethod, string ContentType = "text/html;charset=UTF-8")
  421. {
  422. string retString = "";
  423. HttpWebRequest request = null;
  424. HttpWebResponse response = null;
  425. #region 记录接口日志相关
  426. // InterfaceInvokeLogEntity logInfo = new InterfaceInvokeLogEntity();
  427. string postDataStr = string.Empty;
  428. #endregion
  429. try
  430. {
  431. #region 记录接口日志相关
  432. //用于记录日志 MZ 2017-08-01
  433. postDataStr = GetPostDataStr(dict);
  434. #endregion
  435. string url = apiUrl;
  436. //请求参数
  437. //请求路径
  438. var requestPath = url + (postDataStr == "" ? "" : "?") + postDataStr;
  439. request = (HttpWebRequest)WebRequest.Create(requestPath);
  440. request.Method = strMethod;
  441. if (!string.IsNullOrEmpty(ContentType))
  442. request.ContentType = ContentType;
  443. else
  444. request.ContentType = "text/html;charset=UTF-8";
  445. request.Timeout = 120000;
  446. //获取响应,取出其中的json数据
  447. response = (HttpWebResponse)request.GetResponse();
  448. if (response.StatusCode == HttpStatusCode.OK)
  449. {
  450. Stream myResponseStream = response.GetResponseStream();
  451. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  452. retString = myStreamReader.ReadToEnd();
  453. myStreamReader.Close();
  454. myResponseStream.Close();
  455. #region 记录接口日志相关
  456. //记录调用日志 MZ
  457. #endregion
  458. }
  459. }
  460. catch (WebException ex)
  461. {
  462. try
  463. {
  464. HttpWebResponse res = (HttpWebResponse)ex.Response;
  465. StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
  466. //真正的原因
  467. string errorMessage = sr.ReadToEnd();
  468. //todo:发超时邮件
  469. return null;
  470. }
  471. catch (Exception)
  472. {
  473. }
  474. }
  475. finally
  476. {
  477. }
  478. return retString;
  479. }
  480. public static string GetSign(IDictionary<string, string> parameters, string url, string secret)
  481. {
  482. var builder = new StringBuilder();
  483. builder.Append(url);
  484. builder.Append("\n");
  485. foreach (var param in parameters.OrderBy(t => t.Key))
  486. {
  487. builder.Append(string.Format("{0}={1}\n", param.Key, param.Value));
  488. }
  489. builder.Append(secret);
  490. return GetMd5_2(builder.ToString());
  491. }
  492. public static string GetMd5_2(string src)
  493. {
  494. var buffer = new StringBuilder();
  495. using (var md5 = MD5.Create())
  496. {
  497. var md5Bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(src));
  498. for (var i = 0; i < md5Bytes.Length; i++)
  499. {
  500. var val = Convert.ToInt32(md5Bytes[i] & 0xff);
  501. if (val < 16)
  502. {
  503. buffer.Append("0");
  504. }
  505. buffer.Append(string.Format("{0:X}", val));
  506. }
  507. }
  508. return buffer.ToString();
  509. }
  510. }
  511. }