123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591 |
- 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
- {
- /// <summary>
- /// 获取签名值
- /// </summary>
- /// <param name="parameters"></param>
- /// <param name="url"></param>
- /// <param name="secret"></param>
- /// <returns></returns>
- public static string Sign(IDictionary<string, string> 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();
- }
- /// <summary>
- /// 获取ESB的时间戳,即C#实现java这个方法System.currentTimeMillis(),产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数
- /// </summary>
- /// <param name="time"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 对 URL 字符串进行编码。
- /// </summary>
- /// <param name="dict"></param>
- /// <returns></returns>
- public static string buildEncodeUrl(IDictionary<string, string> 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("&"));
- }
- /// <summary>
- /// http方式获取数据
- /// </summary>
- /// <param name="url"></param>
- /// <param name="requestString"></param>
- /// <param name="method"></param>
- /// <param name="encoding"></param>
- /// <param name="times">请求超时时间(默认60秒)</param>
- /// <returns></returns>
- 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();
- }
- }
- /// <summary>
- /// 检查UPN是否上传到OPPO成功
- /// </summary>
- /// <param name="esbUrl">OPPO的API URL</param>
- /// <param name="appId"></param>
- /// <param name="esbSecret"></param>
- /// <param name="upn">UPN条码</param>
- /// <returns>返回UPN的SN清单</returns>
- 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<String, Object> sendData = new LinkedHashMap<String, Object>();
- IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- StringBuilder builder = new StringBuilder();
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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;
- }
- }
- /// <summary>
- /// 插入电池信息到OPPO
- /// </summary>
- /// <param name="esbUrl"></param>
- /// <param name="appId"></param>
- /// <param name="esbSecret"></param>
- /// <param name="strBatteryList"></param>
- /// <returns>返回oppo插入的电池个数</returns>
- 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<String, Object> sendData = new LinkedHashMap<String, Object>();
- //IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- //StringBuilder builder = new StringBuilder();
- //JavaScriptSerializer json = new JavaScriptSerializer();
- //json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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<String, Object> sendData = new LinkedHashMap<String, Object>();
- IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- StringBuilder builder = new StringBuilder();
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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;
- }
- }
- /// <summary>
- /// 删除UPN接口调用
- /// mes_vendor_upn_inspection_to_del_insert
- /// </summary>
- /// <param name="esbUrl"></param>
- /// <param name="appId"></param>
- /// <param name="esbSecret"></param>
- /// <param name="strUpnlist"></param>
- /// <returns></returns>
- 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<String, Object> sendData = new LinkedHashMap<String, Object>();
- IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- StringBuilder builder = new StringBuilder();
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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;
- }
- }
- /// <summary>
- /// 获取UPN信息
- /// mes_vendor_upn_inspection_to_del_insert
- /// </summary>
- /// <param name="esbUrl"></param>
- /// <param name="appId"></param>
- /// <param name="esbSecret"></param>
- /// <param name="strUpnlist"></param>
- /// <returns></returns>
- 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<String, Object> sendData = new LinkedHashMap<String, Object>();
- IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- StringBuilder builder = new StringBuilder();
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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;
- }
- }
- /// <summary>
- /// 获取锁卡信息接口调用
- /// mes_lock_card_info_list
- /// </summary>
- /// <param name="esbUrl"></param>
- /// <param name="appId"></param>
- /// <param name="esbSecret"></param>
- /// <returns></returns>
- 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<String, Object> sendData = new LinkedHashMap<String, Object>();
- IDictionary<string, Object> sendData = new Dictionary<string, Object>();
- StringBuilder builder = new StringBuilder();
- JavaScriptSerializer json = new JavaScriptSerializer();
- json.Serialize(sendData, builder);
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- //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<string, string> 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<string, string> 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<string, string> 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();
- }
- }
- }
|