using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Security.Cryptography; using System.Net; using System.IO; //using System.Web.Script.Serialization; using System.Web.Script.Serialization; using System.Web; namespace UAS_LabelMachine.PublicMethod { public class HttpCommand { /// /// 获取签名值 /// /// /// /// /// public static string Sign(IDictionary parameters, string url, string secret) { var builder = new StringBuilder(); builder.Append(url); builder.Append("\n"); foreach (var param in parameters.OrderBy(t => t.Key)) { builder.Append(string.Format("{0}={1}\n", param.Key, param.Value)); } builder.Append(secret); return GetMd5(builder.ToString()); } //获取MD5值 public static string GetMd5(string src) { var buffer = new StringBuilder(); using (var md5 = MD5.Create()) { var md5Bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(src)); for (var i = 0; i < md5Bytes.Length; i++) { var val = Convert.ToInt32(md5Bytes[i] & 0xff); if (val < 16) { buffer.Append("0"); } buffer.Append(string.Format("{0:X}", val)); } } return buffer.ToString(); } /// /// 获取ESB的时间戳,即C#实现java这个方法System.currentTimeMillis(),产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数 /// /// /// public static string ConvertTimeStamp(string time) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); DateTime dtNow = DateTime.Parse(time); TimeSpan toNow = dtNow.Subtract(dtStart); string timeStamp = toNow.Ticks.ToString(); timeStamp = timeStamp.Substring(0, timeStamp.Length - 7); return timeStamp; } /// /// 对 URL 字符串进行编码。 /// /// /// public static string buildEncodeUrl(IDictionary dict) { StringBuilder sb = new StringBuilder(); foreach (var param in dict.OrderBy(t => t.Key)) { string encode = HttpUtility.UrlEncode(param.Value, Encoding.UTF8); sb.Append(param.Key).Append("=").Append(encode).Append("&"); } return sb.ToString().Substring(0, sb.ToString().LastIndexOf("&")); } /// /// http方式获取数据 /// /// /// /// /// /// 请求超时时间(默认60秒) /// public static String GetResponseHTML(string url, string requestString, string method, Encoding encoding, int times = 60) { try { if (encoding == null) { encoding = Encoding.UTF8; } if (method == "POST") { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = method; req.ContentType = "application/x-www-form-urlencoded"; req.KeepAlive = false; req.Timeout = times * 1000; req.ReadWriteTimeout = times * 1000; //req.UserAgent = new HttpConfig().RMSUserAgent; //不需要根据http协议版本匹配,不需要进行协议握手就是说 //Expect:100-Continue的作用是,设定Client 和 Server在Post数据前需要进行“请求头域”的数据匹配,相当于是握手。如果匹配则开始进行body 的内容,Post数据。否则,报错(417) Unkown req.ServicePoint.Expect100Continue = false; //传输请求的数据 if (!string.IsNullOrEmpty(requestString)) { byte[] data = encoding.GetBytes(requestString); req.ContentLength = data.Length; using (Stream stream = req.GetRequestStream()) { stream.Write(data, 0, data.Length); //stream.Flush(); stream.Close(); } } //获取回传数据 using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); string content = reader.ReadToEnd(); reader.Close(); return content; } } else { HttpWebRequest req = null; if (string.IsNullOrEmpty(requestString)) { req = (HttpWebRequest)WebRequest.Create(url); } else if (url.IndexOf("?") > 0) { req = (HttpWebRequest)WebRequest.Create(url + "&" + requestString); } else { req = (HttpWebRequest)WebRequest.Create(url + "?" + requestString); } // req.Method = method; req.Timeout = times * 1000; req.ReadWriteTimeout = times * 1000; req.ServicePoint.Expect100Continue = false; req.ContentType = "application/x-www-form-urlencoded"; //获取回传数据 using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); string content = reader.ReadToEnd(); reader.Close(); return content; } } } catch (System.Net.WebException ex) { HttpWebResponse res = (HttpWebResponse)ex.Response; StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8")); string errorMessage = sr.ReadToEnd(); return errorMessage; } catch (Exception e) { //Logger log = new Logger(); //log.LogException(e); return e.ToString(); } } /// /// 检查UPN是否上传到OPPO成功 /// /// OPPO的API URL /// /// /// UPN条码 /// 返回UPN的SN清单 public String checkWmsBatteryInfo(string esbUrl, string appId, string esbSecret, string upn) { string uri = "/mes/extranet/check_wms_battery_info"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); IDictionary sendData = new Dictionary(); StringBuilder builder = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer(); json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); parameters.Add("app_id", appId); parameters.Add("bat_upn", upn); parameters.Add("procstep", "1"); parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("sign", Sign(parameters, uri, esbSecret)); string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), null, null); if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } /// /// 插入电池信息到OPPO /// /// /// /// /// /// 返回oppo插入的电池个数 public String insertBatteryInfo(string esbUrl, string appId, string esbSecret, string strBatteryList) { //string uri = "/mes/basics/wms_battery_info_insert"; string uri = "/mes/extranet/mes_test_result_info_insert"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); //IDictionary sendData = new Dictionary(); //StringBuilder builder = new StringBuilder(); //JavaScriptSerializer json = new JavaScriptSerializer(); //json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); /*注意:参数添加到parameters,必须按参数字母顺序添加*/ parameters.Add("app_id", appId); parameters.Add("test_info", strBatteryList); parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("test_amount", "4"); parameters.Add("sign", Sign(parameters, uri, esbSecret)); string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null); if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } public String insertUpnInfo(string esbUrl, string appId, string esbSecret, string strUpnlist, int count) { //string uri = "/mes/basics/wms_battery_info_insert"; string uri = "/mes/extranet/mes_vendor_upn_inspection_result_insert"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); IDictionary sendData = new Dictionary(); StringBuilder builder = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer(); json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); /*注意:参数添加到parameters,必须按参数字母顺序添加*/ parameters.Add("app_id", appId); parameters.Add("inspection_amount", count.ToString()); parameters.Add("inspection_info", strUpnlist); parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("sign", Sign(parameters, uri, esbSecret)); string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null); Console.WriteLine(result); //{"response":{"code":"200","success_count":2}} if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } /// /// 删除UPN接口调用 /// mes_vendor_upn_inspection_to_del_insert /// /// /// /// /// /// public String deleteUpnInfo(string esbUrl, string appId, string esbSecret, string strUpnlist,int num) { //string uri = "/mes/basics/wms_battery_info_insert"; string uri = "/mes/extranet/mes_vendor_upn_inspection_to_del_insert"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); IDictionary sendData = new Dictionary(); StringBuilder builder = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer(); json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); /*注意:参数添加到parameters,必须按参数字母顺序添加*/ //parameters.Add("app_id", appId); //parameters.Add("inspection_amount", "1"); //parameters.Add("inspection_info", strUpnlist); //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("app_id", appId); //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("upn_amount", num.ToString()); parameters.Add("upn_info", strUpnlist); //inspection_info test_info parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("sign", Sign(parameters, uri, esbSecret)); string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null); Console.Write(result); if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } /// /// 获取UPN信息 /// mes_vendor_upn_inspection_to_del_insert /// /// /// /// /// /// public String getUpnInfo(string esbUrl, string appId, string esbSecret, string strUpn) { //string uri = "/mes/basics/wms_battery_info_insert"; string uri = "/mes/extranet/mes_vendor_upn_process_result_list"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); IDictionary sendData = new Dictionary(); StringBuilder builder = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer(); json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); /*注意:参数添加到parameters,必须按参数字母顺序添加*/ //parameters.Add("app_id", appId); //parameters.Add("inspection_amount", "1"); //parameters.Add("inspection_info", strUpnlist); //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("app_id", appId); //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); // parameters.Add("upn_amount", "2"); parameters.Add("upn_info", strUpn); //inspection_info test_info parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("sign", Sign(parameters, uri, esbSecret)); string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "POST", null); if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } /// /// 获取锁卡信息接口调用 /// mes_lock_card_info_list /// /// /// /// /// public String Getinfo(string esbUrl, string appId, string esbSecret) { //string uri = "/mes/basics/wms_battery_info_insert"; string uri = "/mes/extranet/mes_lock_card_info_list"; Encoding encoding = Encoding.GetEncoding("utf-8"); //Map sendData = new LinkedHashMap(); IDictionary sendData = new Dictionary(); StringBuilder builder = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer(); json.Serialize(sendData, builder); IDictionary parameters = new Dictionary(); //parameters.Add("app_id", "SUP-FMT"); /*注意:参数添加到parameters,必须按参数字母顺序添加*/ //parameters.Add("app_id", appId); //parameters.Add("inspection_amount", "1"); //parameters.Add("inspection_info", strUpnlist); //parameters.Add("timestamp", ConvertTimeStamp(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); parameters.Add("date_from", "20190227001000"); parameters.Add("date_to", "20190228002000"); parameters.Add("page_index", "1"); parameters.Add("page_size", "10"); parameters.Add("app_id", appId); // parameters.Add("upn_info", strUpnlist); //inspection_info test_info parameters.Add("timestamp", ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString()); parameters.Add("sign", GetSign(parameters, uri.Trim(), esbSecret)); string result = HttpGet(parameters, esbUrl + ":80" + uri, "GET"); // string result = GetResponseHTML(esbUrl + uri, buildEncodeUrl(parameters), "GET", null); if ("{\"data\":\"\",\"error_code\":0,\"error_msg\":\"\"}".Equals(result)) { return "Success"; } else { return result; } } public static string GetPostDataStr(IDictionary dict) { string postDataStr = ""; StringBuilder myStringBuilder = new StringBuilder(); foreach (var item in dict) { myStringBuilder.Append(HttpUtility.UrlEncode(item.Key)); myStringBuilder.Append("="); myStringBuilder.Append(HttpUtility.UrlEncode(item.Value)); myStringBuilder.Append("&"); } int lenght = myStringBuilder.ToString().Length; postDataStr = lenght > 1 ? myStringBuilder.ToString().Remove(lenght - 1) : ""; return postDataStr; } public static string HttpGet(IDictionary dict, string apiUrl, string strMethod, string ContentType = "text/html;charset=UTF-8") { string retString = ""; HttpWebRequest request = null; HttpWebResponse response = null; #region 记录接口日志相关 // InterfaceInvokeLogEntity logInfo = new InterfaceInvokeLogEntity(); string postDataStr = string.Empty; #endregion try { #region 记录接口日志相关 //用于记录日志 MZ 2017-08-01 postDataStr = GetPostDataStr(dict); #endregion string url = apiUrl; //请求参数 //请求路径 var requestPath = url + (postDataStr == "" ? "" : "?") + postDataStr; request = (HttpWebRequest)WebRequest.Create(requestPath); request.Method = strMethod; if (!string.IsNullOrEmpty(ContentType)) request.ContentType = ContentType; else request.ContentType = "text/html;charset=UTF-8"; request.Timeout = 120000; //获取响应,取出其中的json数据 response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); #region 记录接口日志相关 //记录调用日志 MZ #endregion } } catch (WebException ex) { try { HttpWebResponse res = (HttpWebResponse)ex.Response; StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8")); //真正的原因 string errorMessage = sr.ReadToEnd(); //todo:发超时邮件 return null; } catch (Exception) { } } finally { } return retString; } public static string GetSign(IDictionary parameters, string url, string secret) { var builder = new StringBuilder(); builder.Append(url); builder.Append("\n"); foreach (var param in parameters.OrderBy(t => t.Key)) { builder.Append(string.Format("{0}={1}\n", param.Key, param.Value)); } builder.Append(secret); return GetMd5_2(builder.ToString()); } public static string GetMd5_2(string src) { var buffer = new StringBuilder(); using (var md5 = MD5.Create()) { var md5Bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(src)); for (var i = 0; i < md5Bytes.Length; i++) { var val = Convert.ToInt32(md5Bytes[i] & 0xff); if (val < 16) { buffer.Append("0"); } buffer.Append(string.Format("{0:X}", val)); } } return buffer.ToString(); } } }