c# 获取海康ISAPI布防 类
时间: 2023-11-22 12:21:31 浏览: 223
获取海康ISAPI布防类的C#代码如下:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace HikvisionISAPI
{
public class HikvisionISAPI
{
private string _ip;
private string _port;
private string _username;
private string _password;
private string _sessionID;
//构造函数
public HikvisionISAPI(string ip, string port, string username, string password)
{
_ip = ip;
_port = port;
_username = username;
_password = password;
_sessionID = string.Empty;
}
//获取登录会话ID
private void GetSessionID()
{
string url = string.Format("https://{0}:{1}/ISAPI/Security/sessionLogin", _ip, _port);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData = string.Format("username={0}&password={1}", _username, _password);
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
XmlNode node = xmlDoc.SelectSingleNode("//SessionID");
if (node != null)
{
_sessionID = node.InnerText;
}
}
//获取布防状态
public string GetAlarmStatus(string channelID)
{
if (string.IsNullOrEmpty(_sessionID))
{
GetSessionID();
}
string url = string.Format("https://{0}:{1}/ISAPI/Event/notification/alertStream/{2}", _ip, _port, channelID);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/xml";
request.Headers.Add("Authorization", "Session " + _sessionID);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseContent = string.Empty;
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseContent = reader.ReadToEnd();
}
return responseContent;
}
//检查证书
private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
}
```
使用方法:
```csharp
//创建 HikvisionISAPI 实例
HikvisionISAPI hik = new HikvisionISAPI("192.168.1.100", "80", "admin", "12345");
//获取通道ID为1的布防状态
string alarmStatus = hik.GetAlarmStatus("1");
Console.WriteLine(alarmStatus);
```
需要注意的是,在调用GetSessionID方法时,需要根据实际情况修改ISAPI的登录接口地址。同时,在请求时需要添加Authorization头部,其值为Session+空格+SessionID。另外,在使用GetAlarmStatus方法获取布防状态时,需要将通道ID作为参数传入。
阅读全文