using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Text; using System.Web.Script.Serialization; using System.Web.Services.Description; using System.Xml; namespace BaseLibComm { /// /// WebService 代理类 /// public class WebServiceAgent { private object agent; private Type agentType; private const string CODE_NAMESPACE = "WebServiceAgent.Dynamic"; private static jsonVMI[] vMI; /// ///调用指定的方法 /// ///方法名 ///动态参数 ///返回 Web service public string Invoke(string methodName, string args) { try { MethodInfo mi = agentType.GetMethod(methodName); ParameterInfo[] arrpi = mi.GetParameters(); var pars = args.Trim().Split(','); ArrayList arr = new ArrayList(); for (int i = 0; i < pars.Length; i++) { if (arrpi[i].ParameterType != typeof(string)) { arr.Add(Convert.ChangeType(pars[i], arrpi[i].ParameterType)); } else { arr.Add(pars[i].Replace("#",",")); } } object ob = this.Invoke(mi, arr.ToArray()); WriteTextLog("日志", ob.ToString(), DateTime.Now); return ob.ToString(); } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// 调用指定的方法 /// /// 分隔符号 /// 方法名 /// 动态参数 /// public string Invoke(string split, string methodName, string args) { try { MethodInfo mi = agentType.GetMethod(methodName); ParameterInfo[] arrpi = mi.GetParameters(); var pars = args.Trim().Split(new[] { split }, StringSplitOptions.None); ArrayList arr = new ArrayList(); for (int i = 0; i < pars.Length; i++) { if (arrpi[i].ParameterType != typeof(string)) { arr.Add(Convert.ChangeType(pars[i], arrpi[i].ParameterType)); } else { arr.Add(pars[i]); } } object ob = this.Invoke(mi, arr.ToArray()); WriteTextLog("日志", ob.ToString(), DateTime.Now); return ob.ToString(); } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// ///调用方法 /// ///方法 ///参数 ///返回 Web service public object Invoke(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } public MethodInfo[] Methods { get { return agentType.GetMethods(); } } /// /// 写入日志到文本文件 /// /// 动作 /// 日志内容 /// 时间 public static void WriteTextLog(string action, string strMessage, DateTime time) { string path = AppDomain.CurrentDomain.BaseDirectory + @"NetLog\"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); string fileFullPath = path + time.ToString("yyyyMMdd") + ".txt"; StringBuilder str = new StringBuilder(); str.Append("Time: " + time.ToString() + "\r\n"); str.Append("Action: " + action + "\r\n"); str.Append("Message: " + strMessage + "\r\n"); str.Append("-----------------------------------------------------------\r\n"); StreamWriter sw; if (!File.Exists(fileFullPath)) { sw = File.CreateText(fileFullPath); } else { sw = File.AppendText(fileFullPath); } sw.WriteLine(str.ToString()); sw.Close(); } /// /// 以Post方式提交命令 /// public static string Post(string apiurl, string jsonString) { return Post(apiurl, jsonString, "utf-8"); } /// /// 以Post方式提交命令 /// public static string Post(string apiurl, string jsonString, string codingName) { try { WebRequest request = WebRequest.Create(@apiurl); request.Method = "POST"; request.ContentType = "application/json"; byte[] bs = Encoding.UTF8.GetBytes(jsonString); request.ContentLength = bs.Length; Stream newStream = request.GetRequestStream(); newStream.Write(bs, 0, bs.Length); newStream.Close(); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(codingName)); string resultJson = reader.ReadToEnd(); return resultJson; //string Url, string postDataStr //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; //request.ContentLength = postDataStr.Length; //StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII); //writer.Write(postDataStr); //writer.Flush(); //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //string encoding = response.ContentEncoding; //if (encoding == null || encoding.Length < 1) //{ // encoding = "UTF-8"; //默认编码 //} //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); //string retString = reader.ReadToEnd(); //return retString; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } public static string Post(string url) { return PostByCoding(url, "utf-8"); } public static string PostByCoding(string url, string codingName) { try { WebRequest request = WebRequest.Create(@url); byte[] bs = Encoding.UTF8.GetBytes(string.Empty); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bs.Length; request.Method = "POST"; System.IO.Stream RequestStream = request.GetRequestStream(); RequestStream.Write(bs, 0, bs.Length); RequestStream.Close(); System.Net.WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(codingName)); string ReturnVal = reader.ReadToEnd(); reader.Close(); response.Close(); return ReturnVal; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// Get方式提交 /// /// /// public static string Get(string url) { return Get(url, "utf-8"); } /// /// 异步Get /// /// /// public static string GetByHttpClient(string url) { HttpClient httpClient = new HttpClient(); var response = httpClient.GetAsync(url).Result; string msg = response.Content.ReadAsStringAsync().Result; return msg; } /// /// 异步Post /// /// /// public static string PostByHttpClient(string url, string pars) { HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); string[] splits = pars.Split('&'); foreach (var item in splits) { string[] keys = item.Split('='); string value = string.Empty; if (keys.Length > 1) { value = keys[1]; } form.Add(new StringContent(value), keys[0]); } var response = httpClient.PostAsync(new Uri(url), form).Result; string msg = response.Content.ReadAsStringAsync().Result; return msg; } /// /// 文件下载 /// /// /// json字符串 /// 文件保存路径 /// public static string DownLoadByHttpClient(string url, string json, string filePath) { try { HttpClient httpClient = new HttpClient(); StringContent content = new StringContent(json); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var response = httpClient.PostAsync(new Uri(url), content).Result; var stream = response.Content.ReadAsStreamAsync().Result; StreamToFile(stream, filePath); return filePath; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); return ""; } } /// /// VMI个案开发 /// /// /// 保存的文件夹路径 /// public static string DownLoadForVMI(string url, string filePath) { try { if (vMI == null) { return ""; } else { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(vMI[0]); string result1=DownLoadByHttpClient(url + "/" + vMI[0].image, json, filePath+ vMI[0].image); json=js.Serialize(vMI[1]); string result2=DownLoadByHttpClient(url + "/" + vMI[1].image, json, filePath + vMI[1].image); vMI = null; return result1+","+ result2; } } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// 将 Stream 写入文件 /// public static void StreamToFile(Stream stream, string fileName) { // 把 Stream 转换成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 写入文件 FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// /// Get方式提交 /// /// /// utf-8 /// public static string Get(string url, string codingName) { try { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "GET"; request.ContentType = "application/json"; request.Headers.Add("charset", codingName); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding(codingName)); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //request.Method = "GET"; //request.ContentType = "text/html;charset=UTF-8"; //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //Stream myResponseStream = response.GetResponseStream(); //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); //string retString = myStreamReader.ReadToEnd(); //myStreamReader.Close(); //myResponseStream.Close(); //return retString; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// Post请求 /// /// /// public static string PostData(string url, string Pars) { return PostData(url, Pars, "utf-8"); } /// /// Post请求 /// /// /// public static string PostData(string url, string Pars, string codingName) { try { WebRequest request = WebRequest.Create(@url); byte[] bs = Encoding.UTF8.GetBytes(Pars); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bs.Length; request.Method = "POST"; System.IO.Stream RequestStream = request.GetRequestStream(); RequestStream.Write(bs, 0, bs.Length); RequestStream.Close(); System.Net.WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(codingName)); string ReturnVal = reader.ReadToEnd(); reader.Close(); response.Close(); return ReturnVal; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } public static string UploadByWebClient(string url, string Pars, string fileFormName, string filePath) { return UploadByWebClient(url, Pars, filePath, "utf-8"); } public static string UploadByWebClient(string url, string Pars, string fileFormName, string filePath, string codingName) { try { var webclient = new WebClient(); NameValueCollection nvc = new NameValueCollection(); string[] splits = Pars.Split('&'); foreach (var item in splits) { string[] keys = item.Split('='); string value = string.Empty; if (keys.Length > 1) { value = keys[1]; } nvc.Add(keys[0], value); } webclient.QueryString = nvc; byte[] buffer = webclient.UploadFile(url, "POST", filePath); var msg = Encoding.GetEncoding(codingName).GetString(buffer); return msg; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// 上传图片 /// /// /// /// 服务端标记key(不是文件名) /// 文件路径 /// public static string UploadPostData(string url, string Pars, string fileFormName, string filePath) { if (Directory.Exists(filePath)) { filePath = Directory.GetFiles(filePath).First(); } string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; /*wr.KeepAlive = true; wr.Credentials = System.Net.CredentialCache.DefaultCredentials;*/ Stream rs = request.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; string[] splits = Pars.Split('&'); foreach (var item in splits) { string[] keys = item.Split('='); string value = string.Empty; if (keys.Length > 1) { value = keys[1]; } rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, keys[0], value); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } if (!string.IsNullOrEmpty(filePath)) { rs.Write(boundarybytes, 0, boundarybytes.Length); /*string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, fileFormName, fileFormName, "text/html");*/ string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n"; string header = string.Format(headerTemplate, fileFormName, Path.GetFileName(filePath)); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); //读取图片流 byte[] byteFile = File.ReadAllBytes(filePath); rs.Write(byteFile, 0, byteFile.Length); } //结束分隔标记 byte[] endBoundary = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(endBoundary, 0, endBoundary.Length); rs.Close(); WebResponse response = null; try { response = request.GetResponse(); Stream stream2 = response.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string msg = reader2.ReadToEnd(); return msg; } catch (Exception ex) { if (response != null) { response.Close(); response = null; } return ex.ToString(); } finally { request = null; } } /// /// 多文件上传 /// /// /// 附加参数格式:key=value&key=value /// 文件key多个用逗号分开 /// 文件路径多个用逗号分开 /// public static string UploadByHttpClient(string url, string pars, string fileFormName, string filePath) { try { HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); if (pars.Length > 0) { string[] splits = pars.Split('&'); foreach (var item in splits) { string[] keys = item.Split('='); string value = string.Empty; if (keys.Length > 1) { value = keys[1]; } form.Add(new StringContent(value), keys[0]); } } string[] fileFormNames = fileFormName.Split(','); string[] filePaths = filePath.Split(','); for (int i = 0; i < fileFormNames.Length; i++) { form.Add(new ByteArrayContent(File.ReadAllBytes(filePaths[i])), fileFormNames[i], Path.GetFileName(filePaths[i])); } var response = httpClient.PostAsync(new Uri(url), form).Result; WriteTextLog("状态", response.ToString(), DateTime.Now); string msg = response.Content.ReadAsStringAsync().Result; return msg; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } public static string UploadByHttpClientForVMI(string url, string pars, string fileFormName, string filePath) { try { HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); if (pars.Length > 0) { string[] splits = pars.Split('&'); foreach (var item in splits) { string[] keys = item.Split('='); string value = string.Empty; if (keys.Length > 1) { value = keys[1]; } form.Add(new StringContent(value), keys[0]); } } string[] fileFormNames = fileFormName.Split(','); string[] filePaths = filePath.Split(','); for (int i = 0; i < fileFormNames.Length; i++) { if (filePaths[i].IndexOf(":")>-0 && filePaths[i].IndexOf(".")>0) { form.Add(new ByteArrayContent(File.ReadAllBytes(filePaths[i])), fileFormNames[i], Path.GetFileName(filePaths[i])); } else { form.Add(new StringContent(filePaths[i]), fileFormNames[i]); } } var response = httpClient.PostAsync(new Uri(url), form).Result; string str = response.ToString(); str = str.Substring(0,str.IndexOf("Version")-2); WriteTextLog("状态", str, DateTime.Now); string msg = response.Content.ReadAsStringAsync().Result; //[{"elapsed_time":23.23218607902527,"front_new":0,"front_old":0,"image":"HZMC18102600WD_Pre_0120181027_083248_annotated.jpg","side":"FRONT","start_time":"2018-10-29 11:25:44.423392","token":"709c3ba8cf6ef60a80e44191cf58509c"},{"back_new":0,"back_old":0,"elapsed_time":23.23218607902527,"image":"HZMC18102600WD_Pre_0220181027_083304_annotated.jpg","side":"BACK","start_time":"2018-10-29 11:25:44.423392","token":"5ad24ec9fb478beab520c354c9d9bf3c"}] JavaScriptSerializer js = new JavaScriptSerializer(); List> list = new List>(); try { vMI = js.Deserialize(msg); list = js.Deserialize>>(msg); foreach (var item in list) { item.Remove("image"); item.Remove("token"); item.Remove("side"); } } catch { } WriteTextLog("记录", str + ";" + msg, DateTime.Now); return str + ";"+js.Serialize(list); } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } /// /// VMI个案开发 /// /// /// 文件key多个用逗号分开 /// 文件路径多个用逗号分开 /// public static string UploadForVMI(string url, string fileFormName, string filePath) { try { string msg = UploadByHttpClientForVMI(url, "", fileFormName, filePath); return msg; } catch (Exception ex) { WriteTextLog("错误", ex.ToString(), DateTime.Now); throw; } } class jsonVMI { public int decision { get; set; } public string image { get; set; } public string side { get; set; } public string token { get; set; } } #region 格式 //var objJson = new //{ // unit_sn = dictStrAllData["unit_sn"], // serials = new // { // top_case = dictStrAllData["top_case"], // bottom_case = dictStrAllData["bottom_case"] // }, // pass = dictStrAllData["pass"], // input_time = dictStrAllData["input_time"], // output_time = dictStrAllData["output_time"], // data = new // { // MeasurementA = dictStrAllData["MeasurementA"], // MeasurementB = dictStrAllData["MeasurementB"], // MeasurementC = dictStrAllData["MeasurementC"], // sw_version = dictStrAllData["sw_version"], // limits_version = dictStrAllData["limits_version"], // }, // limits = new // { // MeasurementA = new // { // upper_limit = dictStrAllData["upper_limit_A"], // lower_limit = dictStrAllData["lower_limit_A"] // }, // MeasurementB = new // { // upper_limit = dictStrAllData["upper_limit_B"] // }, // MeasurementC = new // { // lower_limit = dictStrAllData["lower_limit_C"] // } // }, // attr = new // { // ATTR1 = dictStrAllData["ATTR1"], // ATTR2 = dictStrAllData["ATTR2"] // }, // blobs = new object[] // { // new { file_name = dictStrAllData["file_name_log"] }, // new // { // file_name = dictStrAllData["file_name_image"], // retention_policy= dictStrAllData["retention_policy"] // } // } //}; #endregion } }