using System; using System.Collections.Generic; using System.Configuration; using System.Text; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; using System.Net; using System.Threading; using System.Xml; namespace WinFormsAppVisitorDeploy { public partial class Form1 : Form { public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } /// /// 窗口初始化 /// /// /// public void Form1_Load(object sender, EventArgs e) { StartEventLongHttp(); //开个线程 { Thread T = new Thread(ThreadFunction); //启动新的线程 T.Start(); } } /// /// 定时验证是否收到心跳信息 /// public void ThreadFunction() { while (true) { Thread.Sleep(10000); TimeSpan ts = DateTime.Now - newDataTime; //计算时间差 string time = ts.TotalSeconds.ToString(); //将时间差转换为秒 var timLen = decimal.Parse(time); if (timLen > 30) { AppendShowMsg("心跳超时,重新连接," + timLen + "秒"); LogError("心跳超时,重新连接," + timLen + "秒"); //心跳超时,重新连接 isOne = true; StartEventLongHttp(); AppendShowMsg("心跳超时,重新连接执行结束"); LogError("心跳超时,重新连接执行结束"); } else { //心跳未超时 AppendShowMsg("心跳正常收到数据," + timLen + "秒"); LogDebug("心跳正常收到数据," + timLen + "秒"); } } } /// /// 最新收到信息时间 /// DateTime newDataTime = DateTime.Now; /// /// 访客机服务器IP地址 /// string strDeviceIp = ConfigurationManager.AppSettings["strDeviceIp"].ToString(); /// /// 访客机服务对接接口 /// string sPort = ConfigurationManager.AppSettings["sPort"].ToString(); string strUserName = ConfigurationManager.AppSettings["strUserName"].ToString(); string strPassword = ConfigurationManager.AppSettings["strPassword"].ToString(); string deviceSericeNo = ConfigurationManager.AppSettings["deviceSericeNo"].ToString(); string DistributeUserUrl = ConfigurationManager.AppSettings["DistributeUserUrl"].ToString(); string strUrl = ConfigurationManager.AppSettings["strUrl"].ToString(); public class visitorModel { public string deviceSericeNo { get; set; } public string contentType { get; set; } public string ipAddress { get; set; } public int portNo { get; set; } public string macAddress { get; set; } public string dateTime { get; set; } public int activePostCount { get; set; } public string eventType { get; set; } public string eventState { get; set; } public string eventDescription { get; set; } //public VisitorEvent VisitorEvent { get; set; } public VisitorEvent VisitorEvent = new VisitorEvent(); public int picturesNumber { get; set; } public VisitorInfoSearchEvent VisitorInfoSearchEvent = new VisitorInfoSearchEvent(); } public class VisitorEvent { public string uuid { get; set; } public string name { get; set; } public string sex { get; set; } public string address { get; set; } public string certificateType { get; set; } public string IDNum { get; set; } public string authCode { get; set; } public string phoneNo { get; set; } public string cardNo { get; set; } public bool ORCodeEnabled { get; set; } public string registerType { get; set; } public string masterVisitorUuid { get; set; } public int entourageNum { get; set; } public string registerStatus { get; set; } public string reason { get; set; } public string visitTime { get; set; } public string leaveTime { get; set; } public string appointmentVisitTime { get; set; } public string appointmentLeaveTime { get; set; } public string receptionistName { get; set; } public string receptionistDepartment { get; set; } public string plateNo { get; set; } public string company { get; set; } public string belongings { get; set; } public string remark { get; set; } public VisitorRightList[] VisitorRightList { get; set; } public bool currentEvent { get; set; } public VisitorImage visitorImage = new VisitorImage(); } public class VisitorImage { public string resourcesContentType { get; set; } public string resourcesContent { get; set; } public string resourcesImage { get; set; } } public class VisitorRightList { public string uuid { get; set; } public string remark { get; set; } } public class VisitorInfoSearchEvent { public string searchID { get; set; } public string uuid { get; set; } public string IDNum { get; set; } public string authCode { get; set; } public string phoneNo { get; set; } public string cardNo { get; set; } public string[] registerStatus { get; set; } public string startTime { get; set; } public string endTime { get; set; } } public class VisirtorInfoSearchEventConfirmInfo { public VisitorInfoSearchEventConfirm visitorInfoSearchEventConfirm = new VisitorInfoSearchEventConfirm(); } public class VisitorInfoSearchEventConfirm { public string searchID { get; set; } public string responseStatusStrg { get; set; } public int numOfMatches { get; set; } public int totalMatches { get; set; } } /// /// 手动初始化操作 /// /// /// private void button1_Click(object sender, EventArgs e) { isOne = true; StartEventLongHttp(); } // private StringBuilder szBuffer = new StringBuilder(); private List byBuffer = new List(); public delegate bool ProcessLongLinkData(byte[] data, string boundary); private CredentialCache _credentialCache = null; private string strURL = string.Empty; public delegate bool ProcessSendDate(ref byte[] byBuffer); public static int m_iHttpTimeOut = 5000; const int BUFFER_SIZE = 3 * 1024 * 1024; public bool m_bIsAlarmStart = false; public enum HttpStatus { Http200 = 0, HttpOther, HttpTimeOut } /// /// 添加显示信息 /// /// public void AppendShowMsg(string info) { try { richTextBox1.BeginInvoke(new Action(() => { if (richTextBox1.Text.Length > 50000) { richTextBox1.Text = richTextBox1.Text.Substring(richTextBox1.Text.Length - 10000, 10000); } richTextBox1.AppendText(DateTime.Now.ToString() + "\t" + info); richTextBox1.AppendText(Environment.NewLine); richTextBox1.SelectionStart = richTextBox1.TextLength; richTextBox1.ScrollToCaret(); })); } catch (Exception ex) { LogError("添加显示信息异常:" + ex); } } public class RequestState { // This class stores the State of the request. const int BUFFER_SIZE = 3 * 1024 * 1024; public StringBuilder requestData; public byte[] BufferRead; public HttpWebRequest request; public HttpWebResponse response; public Stream streamResponse; public ProcessLongLinkData processLongLinkData; public string strBoundary; public ProcessSendDate processSendData; public WebException eStatus; public RequestState() { BufferRead = new byte[BUFFER_SIZE]; requestData = new StringBuilder(""); request = null; streamResponse = null; processLongLinkData = null; strBoundary = string.Empty; processSendData = null; eStatus = null; } } public class VisitorEventConfirmJSON { public VisitorEventConfirm VisitorEventConfirm = new VisitorEventConfirm(); } public class VisitorEventConfirm { public string uuid { get; set; } public string result { get; set; } public QRCodeInfo QRCodeInfo = new QRCodeInfo(); } public class QRCodeInfo { public string cardNo { get; set; } public int alid { get; set; } public int times { set; get; } } //private IDeviceTree m_deviceTree = null; ////不知道干嘛用的一段 //public class CSubscribeDeviceMgmt //{ // public CSubscribeDeviceMgmt() // { // SubscribeDeviceMgmt = new CSubscribeDeviceMgmtInter(); // } // public class CSubscribeDeviceMgmtInter // { // public CSubscribeDeviceMgmtInter() // { // DevEventList = new List(); // } // public string eventMode { get; set; }/*必填,字符型,网关布防事件模式:"device"-布防指定设备*/ // /*"DevEventList"依赖于"eventMode"为"device"*/ // public class CDevEventListItem // { // public CDevEventListItem() // { // Dev = new CDev(); // } // public class CDev // { // public string devIndex { get; set; } /*必填,字符型,设备唯一标识*/ // public string uploadMode { get; set; }/*必填,字符型,指定设备的事件布防模式:"all"-订阅设备的全部事件*/ // } // public CDev Dev { get; set; } // } // public List DevEventList { get; set; } // } // public CSubscribeDeviceMgmtInter SubscribeDeviceMgmt { get; set; } //} /// /// 开始执行接收访客机登记信息 /// /// public int StartEventLongHttp() { string strparam = ""; string strHttpMethod = "GET"; string strUrl = "http://" + strDeviceIp + ":" + sPort + "/ISAPI/Event/notification/alertStream"; string strResponse = string.Empty; byBuffer.Clear(); m_bIsAlarmStart = true; int iRet = StartHttpLongLink(strUserName, strPassword, strUrl, strHttpMethod , strparam, new ProcessLongLinkData(ParseAlarmData), ref strResponse, true); if (iRet == (int)HttpStatus.HttpOther) { string statusCode = string.Empty; string statusString = string.Empty; ParserResponseStatus(strResponse, ref statusCode, ref statusString); } //bIsAlarmStart = false; return iRet; } /// /// 匹配相同的子byte数组 /// /// 目标byte序列 /// 从目标序列的index位置开始匹配 /// 用来匹配的序列 /// 参数错误或未匹配到返回-1,否则返回value在src上出现的位置 internal int IndexOf(byte[] src, int index, byte[] value) { try { if (src == null || value == null) { return -1; } if (src.Length == 0 || src.Length < index || value.Length == 0 || src.Length < value.Length) { return -1; } for (int i = index; i < src.Length - value.Length; i++) { if (src[i] == value[0]) { if (value.Length == 1) { return i; } bool flag = true; for (int j = 1; j < value.Length; j++) { if (src[i + j] != value[j]) { flag = false; break; } } if (flag) { return i; } } } } catch (Exception ex) { LogError("数组匹配异常:" + ex); } return -1; } public string m_Boundary = "boundary"; string strdatatime = ""; int piccount = 0; public class CHeartBeat { public CHeartBeat() { EventNotificationAlert = new CEventNotificationAlert(); } public class CEventNotificationAlert { public string dataTime { get; set; } public int activePostCount { get; set; } public string eventType { get; set; } public string eventState { get; set; } public string eventDescription { get; set; } } public CEventNotificationAlert EventNotificationAlert { get; set; } } public bool ParseAlarmData(byte[] sourcedata, string boundary) { try { byBuffer.AddRange(sourcedata); byte[] data = byBuffer.ToArray(); if (boundary.Length <= 0) { return false; } if (!m_bIsAlarmStart) { return false; } byte[] bBoundary = System.Text.Encoding.Default.GetBytes("--" + boundary + "\r\n"); int iIndex = this.IndexOf(data, 0, bBoundary); ; int iLen = 0; while (iIndex >= 0) { iIndex += bBoundary.Length; // byte[] bContenttype = System.Text.Encoding.Default.GetBytes("Content-Type:"); int iIndexNext = this.IndexOf(data, iIndex, bContenttype); if (iIndexNext < 0) { break; } iIndexNext += bContenttype.Length; byte[] brn = System.Text.Encoding.Default.GetBytes("\r\n"); int iIndexEnd = this.IndexOf(data, iIndexNext, brn); if (iIndexEnd < 0) { break; } iIndexEnd += brn.Length; string strType = System.Text.Encoding.Default.GetString(data, iIndexNext, iIndexEnd - iIndexNext).Trim(); /////// byte[] bContentlen = System.Text.Encoding.Default.GetBytes("Content-Length:"); iIndexNext = this.IndexOf(data, iIndex, bContentlen); if (iIndexNext < 0) { break; } iIndexNext += bContentlen.Length; byte[] brnrn = System.Text.Encoding.Default.GetBytes("\r\n\r\n"); iIndexEnd = this.IndexOf(data, iIndexNext, brnrn); if (iIndexEnd < 0) { break; } iIndexEnd += brnrn.Length; string strLen = System.Text.Encoding.Default.GetString(data, iIndexNext, iIndexEnd - iIndexNext).Trim(); // string strLen = strReport.Substring(iIndexNext, iIndexEnd - iIndexNext); int iLendata = 0; if (!int.TryParse(strLen, out iLendata) || (iIndexEnd + iLendata) > data.Length) { break; } iIndexNext = iIndexEnd + iLendata; if (strType.Contains("xml")) { string strXml = System.Text.Encoding.Default.GetString(data, iIndexEnd, iLendata).Trim(); //string strXml = strXml.Substring(iIndexEnd, iLenXML); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(strXml); XmlNode rootNode = xmlDoc.DocumentElement; string strIP = string.Empty; string strPort = string.Empty; string strTime = string.Empty; string strChannel = string.Empty; string strAlarmType = string.Empty; XmlNode eventStateNode = null; for (int i = 0; i < rootNode.ChildNodes.Count; i++) { if (rootNode.ChildNodes[i].Name == "eventState") { eventStateNode = rootNode.ChildNodes[i]; } if (rootNode.ChildNodes[i].Name == "ipAddress") { strIP = rootNode.ChildNodes[i].InnerText; } if (rootNode.ChildNodes[i].Name == "portNo") { strPort = rootNode.ChildNodes[i].InnerText; } if (rootNode.ChildNodes[i].Name == "dateTime") { strTime = rootNode.ChildNodes[i].InnerText; string strTmp = strTime.Substring(0, strTime.IndexOf("T")); strTime = strTime.Substring(strTime.IndexOf("T") + 1) + " " + strTmp; } if (rootNode.ChildNodes[i].Name == "channelID") { strChannel = rootNode.ChildNodes[i].InnerText; } if (rootNode.ChildNodes[i].Name == "eventType") { strAlarmType = rootNode.ChildNodes[i].InnerText; } } if (eventStateNode != null && eventStateNode.InnerText.ToLower() != "inactive") { strdatatime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff"); piccount = 0; ListViewItem lvi = new ListViewItem(); lvi.Text = strIP; lvi.SubItems.Add(strAlarmType); lvi.SubItems.Add(strTime); lvi.SubItems.Add(strXml); //m_SyncContext.Post(SetTextSafePost, lvi); } } else if (strType.Contains("json")) { string strJson = System.Text.Encoding.UTF8.GetString(data, iIndexEnd, iLendata).Trim(); if (strJson.Contains("SubscribeDeviceMgmtRsp")) { //订阅回复,显示一下 ListViewItem lvi = new ListViewItem(); lvi.Text = ""; lvi.SubItems.Add("SubscribeDeviceMgmtRsp"); lvi.SubItems.Add(strJson); //m_SyncContext.Post(SetTextSafePost, lvi); } else if (strJson.ToLower().Contains("\"heartbeat\"")) { //心跳 显示一下 CHeartBeat heartBeat = JsonConvert.DeserializeObject(strJson); ListViewItem lvi = new ListViewItem(); lvi.Text = heartBeat.EventNotificationAlert.dataTime; lvi.SubItems.Add(heartBeat.EventNotificationAlert.eventType); lvi.SubItems.Add(strJson); //m_SyncContext.Post(SetTextSafePost, lvi); } else { //其他报警,显示一下 ListViewItem lvi = new ListViewItem(); lvi.Text = ""; lvi.SubItems.Add("Unknown Alarm"); lvi.SubItems.Add(strJson); //m_SyncContext.Post(SetTextSafePost, lvi); } } else if (strType.Contains("image")) { piccount = piccount + 1; string strFileSavePath = "C:\\ISAPI_Alarm_Guard"; if (!Directory.Exists(strFileSavePath)) { Directory.CreateDirectory(strFileSavePath); } byte[] imagetemp = new byte[iLendata]; Array.Copy(data, iIndexEnd, imagetemp, 0, iLendata); if (piccount == 1) { strFileSavePath = strFileSavePath + "\\" + strdatatime + "_visible.jpg"; FileStream fs = new FileStream(strFileSavePath, FileMode.Create); fs.Write(imagetemp, 0, iLendata); fs.Close(); //this.VisiblePicBox.Image = Image.FromFile(strFileSavePath); } else if (piccount == 2) { strFileSavePath = strFileSavePath + "\\" + strdatatime + "_thermal.jpg"; FileStream fs = new FileStream(strFileSavePath, FileMode.Create); fs.Write(imagetemp, 0, iLendata); fs.Close(); //this.ThermalPicBox.Image = Image.FromFile(strFileSavePath); } } iLen = iIndexNext; if (iIndexNext + bBoundary.Length < data.Length) { iIndex = this.IndexOf(data, iIndexNext + bBoundary.Length, bBoundary); } else { iIndex = -1; } } if (iLen > 0) { //szBuffer.Remove(0, iLen); byBuffer.RemoveRange(0, iLen); } return true; } catch (Exception e) { AppendShowMsg("ParseAlarmData方法执行异常:" + e.Message); LogError("ParseAlarmData方法执行异常" + e); return false; } } //private void SetTextSafePost(object lvi) //{ // if (AlarmabsListView.Items.Count > 100) // { // AlarmabsListView.Items.RemoveAt(100); // } // ListViewItem temp = lvi as ListViewItem; // AlarmabsListView.Items.Insert(0, temp); // //AlarmdetailTBox.Text = temp.SubItems[3].Text; //} ////不知道干嘛用的一段 //public class ContantData //{ // public string ContentType { get; set; } // public byte[] Content { get; set; } //} public class PackageData { public byte[] Data; public byte[] HeaderData; public byte[] BodyData; } public Byte[] endArr = new Byte[0]; public List SplitPackage(byte[] data) { string d = System.Text.Encoding.UTF8.GetString(endArr); byte[] pBuf = new byte[endArr.Length + data.Length]; endArr.CopyTo(pBuf, 0); data.CopyTo(pBuf, endArr.Length); string test = System.Text.Encoding.UTF8.GetString(pBuf); List list = new List(); int sindex = 0; int endindex = 0; for (int i = 0; i < pBuf.Length; i++) { try { if (pBuf[i] == 45 && pBuf[i + 1] == 45 && pBuf[i + 2] == 77 && pBuf[i + 3] == 73 && pBuf[i + 4] == 77 && pBuf[i + 5] == 69 && pBuf[i + 6] == 95 && pBuf[i + 7] == 98 && pBuf[i + 8] == 111 && pBuf[i + 9] == 117 && pBuf[i + 10] == 110 && pBuf[i + 11] == 100 && pBuf[i + 12] == 97 && pBuf[i + 13] == 114 && pBuf[i + 14] == 121 && i > 10) { endindex = i; PackageData pd = new PackageData(); int len = i - sindex; pd.Data = new byte[len]; Array.Copy(pBuf, sindex, pd.Data, sindex, len); int index = 0; for (int j = 0; j < pd.Data.Length - 3; j++) { if (pd.Data[j] == 13 && pd.Data[j + 1] == 10 && pd.Data[j + 2] == 13 && pd.Data[j + 3] == 10) { index = j; } } pd.HeaderData = new byte[index]; pd.BodyData = new byte[pd.Data.Length - index - 4]; Array.Copy(pBuf, 0, pd.HeaderData, 0, index); Array.Copy(pBuf, index + 4, pd.BodyData, 0, pd.Data.Length - index - 4); list.Add(pd); sindex = i + 16; } else { } } catch (Exception e) { AppendShowMsg("SplitPackage:" + e.Message); } } int endLength = pBuf.Length - endindex; endArr = new Byte[endLength]; Array.Copy(pBuf, endindex, endArr, 0, endLength); return list; } public int ParserResponseStatus(string httpBody, ref string statusCode, ref string statusString) { if (httpBody == "Timeout") { return 0; } try { if (httpBody != string.Empty) { XmlDocument xml = new XmlDocument(); xml.LoadXml(httpBody); if (xml.DocumentElement != null && xml.DocumentElement.Name == "ResponseStatus") { XmlNodeList childNode = xml.DocumentElement.ChildNodes; foreach (XmlNode node in childNode) { if (node.Name == "statusCode") { statusCode = node.InnerText; } if (node.Name == "statusString") { statusString = node.InnerText; } } } } } catch (Exception e) { statusString = httpBody; AppendShowMsg("ParserResponseStatus方法执行异常:" + e.Message); LogDebug("ParserResponseStatus方法执行异常:" + e); } return 0; } private CredentialCache GetCredentialCache(string sUrl, string strUserName, string strPassword) { if (_credentialCache == null) { _credentialCache = new CredentialCache(); _credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword)); strURL = sUrl; } if (strURL != sUrl) { try { _credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential(strUserName, strPassword)); strURL = sUrl; } catch (Exception ex) { LogError("添加缓存用户信息异常:" + ex); } } return _credentialCache; } /// /// 此处是回调信息,如果不回调就重新注册 /// /// private void ReceiveData(IAsyncResult asyncResult) { try { //最新回调反馈时间 newDataTime = DateTime.Now; RequestState myRequestState = (RequestState)asyncResult.AsyncState; Stream responseStream = myRequestState.streamResponse; int read = responseStream.EndRead(asyncResult); if (read > 0) { if (myRequestState.processLongLinkData != null) { string a = System.Text.Encoding.UTF8.GetString(myRequestState.BufferRead).TrimEnd('\0'); AppendShowMsg(a); AppendShowMsg("*********************"); LogInfo(a); Byte[] pBuf = new Byte[read]; Array.Copy(myRequestState.BufferRead, pBuf, read); //分包 List list = SplitPackage(pBuf); //int flagindex = 0; //遍历包 for (int i = 0; i < list.Count; i++) { //string Data = System.Text.Encoding.UTF8.GetString(list[i].Data); string headerText = System.Text.Encoding.UTF8.GetString(list[i].HeaderData); if (headerText.IndexOf("application/json") > -1) //文字 { ConfirmEvent(list[i].BodyData); } else if (headerText.IndexOf("image/jpeg") > -1) { string countid = headerText.Substring(headerText.LastIndexOf(":") + 1, headerText.Length - headerText.LastIndexOf(":") - 1); SaveImage(countid, list[i].BodyData); } } IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReceiveData), myRequestState); } return; } else { responseStream.Close(); } } catch (Exception ex) { LogError("ReceiveData方法执行异常:" + ex); AppendShowMsg("ReceiveData方法执行异常:" + ex); } } /// /// 保存图片 /// /// /// private void SaveImage(string countid, Byte[] data) { try { string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); LogInfo(bodyText); byte[] picBytes = data; //抓拍图片 string strPic = ""; if (picBytes.Length > 0) { //string path = null; //string szInfo = "VisibleLightPic"; //Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); //string filepath = "D:/Picture/ACSO/" + DateTime.Now.ToString("d"); //if (Directory.Exists(filepath) == false)//如果不存在就创建file文件夹 //{ // Directory.CreateDirectory(filepath); //} //path = string.Format(@"{0}/ACS_LocalTime{1}_{2}.jpeg", filepath, szInfo, rand.Next()); //using (FileStream fs = new FileStream(path, FileMode.Create)) //{ int iLen = (int)picBytes.Length; byte[] by = new byte[iLen]; Array.Copy(picBytes, by, picBytes.Length); //fs.Write(by, 0, iLen); //fs.Close(); strPic = Convert.ToBase64String(by); //} visitorModel visitormodel = new visitorModel(); visitormodel.deviceSericeNo = deviceSericeNo; //标识设备号 visitormodel.VisitorEvent.visitorImage.resourcesContent = countid; visitormodel.VisitorEvent.visitorImage.resourcesImage = strPic; visitormodel.contentType = "image"; string requestURI = strUrl; string requestMethod = "POST"; string json = JsonConvert.SerializeObject(visitormodel); //将数据发送给网络服务 string flag = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" //发送给下发服务 string requestURI2 = DistributeUserUrl; string requestMethod2 = "POST"; string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name + "\",\"rightPlan\":\"1\",\"imgData\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesImage + "\",\"type\":\"1\",\"controltype\":\"add\"}"; string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" LogInfo("SaveImage_发送给下发服务_发送JSON:" + flag2); LogInfo("SaveImage_发送给网络服务_发送图片:" + flag); } } catch (Exception ex) { AppendShowMsg("保存图片异常:" + ex); LogError("保存图片异常:" + ex); } } private void ConfirmEvent(Byte[] data) { try { string bodyText = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0'); LogInfo(bodyText); visitorModel visitormodel = new visitorModel(); visitormodel = JsonConvert.DeserializeObject(bodyText); if (visitormodel == null) { return; } if (visitormodel.eventType == "VisitorEvent") { if (visitormodel.VisitorEvent.currentEvent == false) //离线数据需要返回确认 { string strHttpMethod = "PUT"; string strUrl = "http://" + strDeviceIp + ":" + sPort + "/ISAPI/AccessControl/visitorEventConfirm"; string uuid = visitormodel.VisitorEvent.uuid; string cardNo = visitormodel.VisitorEvent.cardNo; VisitorEventConfirmJSON visitorEventConfirmJSON = new VisitorEventConfirmJSON(); visitorEventConfirmJSON.VisitorEventConfirm.uuid = uuid; //visitormodel.VisitorEvent.uuid; visitorEventConfirmJSON.VisitorEventConfirm.result = "success"; visitorEventConfirmJSON.VisitorEventConfirm.QRCodeInfo.cardNo = cardNo; //visitormodel.VisitorEvent.cardNo; visitorEventConfirmJSON.VisitorEventConfirm.QRCodeInfo.alid = 1; visitorEventConfirmJSON.VisitorEventConfirm.QRCodeInfo.times = 100; string strparam = JsonConvert.SerializeObject(visitorEventConfirmJSON); string strResponse = string.Empty; var request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Method = strHttpMethod; reqList.Add(request); //获取 WebClient client = new WebClient(); client.Credentials = new NetworkCredential(strUserName, strPassword); client.BaseAddress = "http://" + strDeviceIp; client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); client.Headers.Add("ContentLength", strResponse); string str = JsonConvert.SerializeObject(visitorEventConfirmJSON); byte[] bytes = Encoding.UTF8.GetBytes(str); byte[] responseData = client.UploadData(strUrl, "PUT", bytes); //string ss = System.Text.Encoding.UTF8.GetString(responseData); } visitormodel.deviceSericeNo = deviceSericeNo; // 标识设备号 visitormodel.contentType = "json"; string requestURI = strUrl; string requestMethod = "POST"; string json = JsonConvert.SerializeObject(visitormodel); //将数据发送给网络服务 string flag1 = SendHttpRequest(requestURI, requestMethod, json);//返回"true","false" LogInfo("ConfirmEvent_发送给网络服务_发送JSON:" + flag1); string controltype = ""; if (visitormodel.VisitorEvent.registerStatus == "registered") { controltype = "add"; } else { controltype = "del"; } //发送给下发服务 string requestURI2 = DistributeUserUrl; string requestMethod2 = "POST"; string json2 = "{\"uuid\":\"" + visitormodel.VisitorEvent.uuid + "\",\"employeeNo\":\"" + visitormodel.VisitorEvent.visitorImage.resourcesContent.Replace("-", "") + "\",\"name\":\"" + visitormodel.VisitorEvent.name + "\",\"rightPlan\":\"1\",\"imgData\":\"\",\"type\":\"0\",\"controltype\":\"" + controltype + "\"}"; string flag2 = SendHttpRequest(requestURI2, requestMethod2, json2);//返回"true","false" LogInfo("ConfirmEvent_发送给下发服务_发送JSON:" + flag2); } else if (visitormodel.eventType == "VisitorInfoSearchEvent") { } } catch (Exception e) { AppendShowMsg("ConfirmEvent方法执行异常:" + e); LogError("ConfirmEvent方法执行异常:" + e); } } private void RespCallback(IAsyncResult asynchronousResult) { // State of request is asynchronous. RequestState myRequestState = (RequestState)asynchronousResult.AsyncState; try { HttpWebRequest myHttpWebRequest = myRequestState.request; myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult); string strBoundary = myRequestState.response.ContentType; int nIndex = strBoundary.IndexOf("boundary="); if (nIndex >= 0) { strBoundary = strBoundary.Substring(nIndex + "boundary=".Length); myRequestState.strBoundary = strBoundary; } // Read the response into a Stream object. Stream responseStream = myRequestState.response.GetResponseStream(); myRequestState.streamResponse = responseStream; // Begin the Reading of the contents of the HTML page and print it to the console. IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReceiveData), myRequestState); string str = System.Text.Encoding.UTF8.GetString(myRequestState.BufferRead).Trim('\0'); //下发高级配置 string strHttpMethod = "PUT"; string strUrl = "http://" + strDeviceIp + ":" + sPort + "/ISAPI/AccessControl/visitorAdvanceParamCfg"; string strparam = "{\"VisitorAdvanceParamCfg\": {\"autoSyncInfoEnabled\": false,\"autoSyncInfoTimeInterval\": 10,\"visitorAppointEnabled\": false,\"currentEventConfirmEnabled\": false}}"; string strResponse = string.Empty; var request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Method = strHttpMethod; reqList.Add(request); //获取 WebClient client = new WebClient(); client.Credentials = new NetworkCredential(strUserName, strPassword); client.BaseAddress = "http://" + strDeviceIp; client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); client.Headers.Add("ContentLength", strResponse); byte[] bytes = Encoding.UTF8.GetBytes(strparam); byte[] responseData = client.UploadData(strUrl, "PUT", bytes); return; } catch (Exception e) { // myRequestState.eStatus = e; LogError("RespCallback方法执行异常:" + e); AppendShowMsg("RespCallback方法执行异常:" + e); //***Reconnection(); } } List reqList = new List(); bool isOne = true; public int StartHttpLongLink(string strUserName, string strPassword, string strUrl, string strHttpMethod , string strparam, ProcessLongLinkData processLongLinkData, ref string strResponse, bool bBlock = true) { try { //验证是否需要断开连接重新初始化 if (isOne) { isOne = false; //遍历断开所有缓存连接 for (int i = 0; i < reqList.Count; i++) { try { reqList[i].Abort(); } catch (Exception ex) { LogError("重连处理中断开连接异常" + ex); } } reqList.Clear(); } ; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Credentials = GetCredentialCache(strUrl, strUserName, strPassword); request.Method = strHttpMethod; request.KeepAlive = true; // *********** request.ProtocolVersion = HttpVersion.Version11;//*************** reqList.Add(request); if (!string.IsNullOrEmpty(strparam)) { byte[] bs = Encoding.ASCII.GetBytes(strparam); request.ContentType = "application/x-www-form-urlencoded"; //request.ContentType = "application/xml"; request.ContentLength = bs.Length; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } } RequestState myRequestState = new RequestState(); myRequestState.request = request; myRequestState.processLongLinkData = processLongLinkData; var ret = request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); if (bBlock) { int nTimeoutLimit = m_iHttpTimeOut / 100; int nTimeoutCount = 0; while (!ret.IsCompleted && nTimeoutCount < nTimeoutLimit) { Thread.Sleep(100); nTimeoutCount++; } if (nTimeoutCount == nTimeoutLimit) { request.Abort(); } if (myRequestState.response != null && myRequestState.response.StatusCode == HttpStatusCode.OK) { return (int)HttpStatus.Http200; } else { if (myRequestState.eStatus != null) { if (myRequestState.eStatus.Response != null) { Stream st = myRequestState.eStatus.Response.GetResponseStream(); StreamReader sr = new StreamReader(st, System.Text.Encoding.Default); strResponse = sr.ReadToEnd(); AppendShowMsg(strResponse.ToString()); LogInfo(strResponse); sr.Close(); st.Close(); return (int)HttpStatus.HttpOther; } else { strResponse = myRequestState.eStatus.Status.ToString(); AppendShowMsg(strResponse.ToString()); LogInfo(strResponse); return (int)HttpStatus.HttpTimeOut; } } AppendShowMsg(HttpStatus.HttpOther.ToString()); LogInfo(HttpStatus.HttpOther.ToString()); return (int)HttpStatus.HttpOther; } } else { AppendShowMsg(HttpStatus.HttpOther.ToString()); LogInfo(HttpStatus.HttpOther.ToString()); return (int)HttpStatus.Http200; } } catch (WebException ex) { WebResponse wr = ex.Response; AppendShowMsg(ex.Message); LogError(ex.Message); AppendShowMsg("StartHttpLongLink:" + ex.Message); if (wr != null) { return (int)HttpStatus.HttpOther; } else { return (int)HttpStatus.HttpTimeOut; } } catch (Exception exc) { AppendShowMsg("StartHttpLongLink方法执行异常:" + exc); LogError("StartHttpLongLink方法执行异常:" + exc); return 99; } } /// /// 记录普通信息 /// /// private void LogInfo(string msg) { MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Info, path = "Info" }); } /// /// 记录错误信息 /// /// private void LogError(string msg) { MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Error, path = "Error" }); } /// /// 记录调试信息 /// /// private void LogDebug(string msg) { MyLogHelper.WriteMsg(new LogInfoMo() { message = msg, msgType = EnumLogMsgTypeEnum.Debug, path = "Error" }); } public string SendHttpRequest(string requestURI, string requestMethod, string json) { string ReqResult = ""; try { //json格式请求数据 string requestData = json; //拼接URL string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); //post请求 myRequest.Method = requestMethod; if (true)// (requestData != "") { //utf-8编码 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(requestData); myRequest.ContentLength = buf.Length; myRequest.Timeout = 5000; //指定为json否则会出错 myRequest.ContentType = "application/json"; //myRequest.ContentType = "application/x-www-form-urlencoded "; myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; Stream newStream = myRequest.GetRequestStream(); newStream.Write(buf, 0, buf.Length); newStream.Close(); } //获得接口返回值 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")); ReqResult = reader.ReadToEnd(); reader.Close(); myResponse.Close(); } catch (Exception e) { ReqResult = e.Message; AppendShowMsg("SendHttpRequest:" + e.Message); } return ReqResult; } /// /// 窗体关闭事件 /// /// /// private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { System.Environment.Exit(1); } catch (Exception ex) { LogError("强制退出1异常:" + ex); } try { System.Environment.Exit(0); } catch (Exception ex) { LogError("强制退出0异常:" + ex); } } } }