using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace Model { /// /// MES系统交互帮助类 /// public class HttpHalper { /// /// MES验证用户名 /// private static string MES_UserName = ConfigurationManager.ConnectionStrings["MES_UserName"].ConnectionString; /// /// MES验证密码 /// private static string MES_PassWord = ConfigurationManager.ConnectionStrings["MES_PassWord"].ConnectionString; /// /// 连接测试地址 /// private static string MES_ConnTest = ConfigurationManager.ConnectionStrings["MES_ConnTest"].ConnectionString; /// /// 通用数据上传地址 /// private static string MES_ConnUpload = ConfigurationManager.ConnectionStrings["MES_ConnUpload"].ConnectionString; /// /// HTTP请求的返回值 /// private static string json { get; set; } /// /// Get请求 /// /// URL连接地址 /// HTTP请求响应状态,成功时为“OK” private static string GetResponse(string url) { try { if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; } json = ""; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string bstr = Convert.ToBase64String(Encoding.Default.GetBytes(MES_UserName + ":" + MES_PassWord)); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", bstr); HttpResponseMessage response = httpClient.GetAsync(url).Result; string statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) { json = response.Content.ReadAsStringAsync().Result; } httpClient.Dispose(); response.Dispose(); return json; } catch (Exception ex) { throw ex; } } /// /// Post请求 /// /// /// post数据 /// HTTP请求响应状态,成功时为“OK” private static string PostResponse(string url, string postData) { try { json = ""; if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; } //需要登入验证 进行访问 //HttpContent httpContent = new StringContent(postData); //httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //httpContent.Headers.ContentType.CharSet = "utf-8"; //HttpClient httpClient = new HttpClient(); //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //string bstr = Convert.ToBase64String(Encoding.Default.GetBytes(MES_UserName + ":" + MES_PassWord)); //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", bstr); ////httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); //HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; //string statusCode = response.StatusCode.ToString(); //if (response.IsSuccessStatusCode) //{ // json = response.Content.ReadAsStringAsync().Result; //} //httpClient.Dispose(); //httpContent.Dispose(); //response.Dispose(); //无需登入 直接访问 HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; string statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) { json = response.Content.ReadAsStringAsync().Result; } httpClient.Dispose(); httpContent.Dispose(); response.Dispose(); } catch (Exception ex) { throw ex; } return json; } /// /// MES连接测试 /// /// public static MesReturnValue ConnTest() { string str= GetResponse(MES_ConnTest); return JsonToObj(str); } /// /// 上传数据 /// /// /// public static MesReturnValue DataUoload(List list) { UplaodAjxa aa = new UplaodAjxa(); aa.data = list; string jsona = ObjToJson(aa); RecordRemoteSensingLog("Upload=>" + jsona);//记录上传值 string a = PostResponse(MES_ConnUpload, jsona); RecordRemoteSensingLog("ReturnPer=>" + a); //记录返回值 return jss.Deserialize(a); } /// /// js 序列化器 /// static JavaScriptSerializer jss = new JavaScriptSerializer(); #region 1、将对象转换成Json字符创 /// /// 将对象转换成Json字符创(泛型) /// /// /// public static string ObjToJson(object obj) { return jss.Serialize(obj); } #endregion #region 2、将Json还原成对象(泛型) /// /// 将Json还原成对象(泛型) /// /// /// /// public static T JsonToObj(string json) { //var deserializedResult = jss.Deserialize>(json); var deserializedResult = jss.Deserialize(json); return deserializedResult; } #endregion #region 记录远程交互信息 static string path; static string paths; /// /// 打开的文件流对象 /// static FileStream FS { get; set; } static byte[] data { get; set; } /// /// 记录远程交互信息 /// /// private static void RecordRemoteSensingLog(string json) { try { path = @"E:\\MesUploadLog"; paths = @"E:\\MesUploadLog\" + DateTime.Now.ToString("D") + ".txt"; //创建文件夹 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //打开或创建文件 FS = File.Open(paths, FileMode.Append); //获得字节数组 data = System.Text.Encoding.Default.GetBytes(json + "|" + DateTime.Now.ToString() + "\r\n"); //开始写入 FS.Write(data, 0, data.Length); //清空缓冲区、关闭流 FS.Flush(); FS.Close(); } catch (Exception) { throw; } } #endregion } /// /// 上传数据Ajxa格式 /// /// internal class UplaodAjxa { public List data { get; set; } } }