You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

262 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace DS.Module.DjyRulesEngine
{
/// <summary>
/// 大简云规则引擎服务封装请求工具类
/// </summary>
public class RuleEngineHttpUtil
{
/// 平台ip
/// </summary>
private static string _ip;
/// <summary>
/// 平台端口
/// </summary>
private static int _port = 443;
/// <summary>
/// 平台APPKey
/// </summary>
private static string _appkey;
/// <summary>
/// 平台APPSecret
/// </summary>
private static string _secret;
/// <summary>
/// 是否使用HTTPS协议
/// </summary>
private static bool _isHttps = true;
/// <summary>
/// 设置信息参数
/// </summary>
/// <param name="appkey">合作方APPKey</param>
/// <param name="secret">合作方APPSecret</param>
/// <param name="ip">平台IP</param>
/// <param name="port">平台端口默认HTTPS的443端口</param>
/// <param name="isHttps">是否启用HTTPS协议默认HTTPS</param>
/// <return></return> string appkey, string secret,
public static void SetPlatformInfo(string ip, int port = 443, bool isHttps = true)
{
//_appkey = appkey;
//_secret = secret;
_ip = ip;
_port = port;
_isHttps = isHttps;
// 设置并发数如不设置默认为2
ServicePointManager.DefaultConnectionLimit = 512;
}
/// <summary>
/// HTTP GET请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/cameras/indexCode?cameraIndexCode=a10cafaa777c49a5af92c165c95970e0</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <returns></returns>
public static string HttpGet(string uri, int timeout)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, "", false);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "GET";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("USER_KEY"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("USER_SECRET"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
//if (headerKey.Contains("sign"))
//{
// req.Headers.Add(headerKey + ":" + header[headerKey]);
//}
}
HttpWebResponse rsp = null;
try
{
rsp = (HttpWebResponse)req.GetResponse();
if (HttpStatusCode.OK == rsp.StatusCode)
{
Stream rspStream = rsp.GetResponseStream(); // 响应内容字节流
StreamReader sr = new StreamReader(rspStream);
string strStream = sr.ReadToEnd();
long streamLength = strStream.Length;
byte[] response = System.Text.Encoding.UTF8.GetBytes(strStream);
rsp.Close();
return System.Text.Encoding.UTF8.GetString(response);
}
else if (HttpStatusCode.Found == rsp.StatusCode || HttpStatusCode.Moved == rsp.StatusCode) // 302/301 redirect
{
string reqUrl = rsp.Headers["Location"].ToString(); // 获取重定向URL
WebRequest wreq = WebRequest.Create(reqUrl); // 重定向请求对象
WebResponse wrsp = wreq.GetResponse(); // 重定向响应
long streamLength = wrsp.ContentLength; // 重定向响应内容长度
Stream rspStream = wrsp.GetResponseStream(); // 响应内容字节流
byte[] response = new byte[streamLength];
rspStream.Read(response, 0, (int)streamLength); // 读取响应内容至byte数组
rspStream.Close();
rsp.Close();
return System.Text.Encoding.UTF8.GetString(response);
}
rsp.Close();
}
catch (WebException e)
{
if (rsp != null)
{
rsp.Close();
}
}
return null;
}
/// <summary>
/// HTTP Post请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/org/advance/orgList</param>
/// <param name="body">请求参数</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <return>请求结果</return>
public static string HttpPost(string uri, string body, int timeout)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, body, true);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
// 创建POST请求
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "POST";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
req.UserAgent = "PostmanRuntime/7.26.8";
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("USER_KEY"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("USER_SECRET"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
//if (headerKey.Contains("sign"))
//{
// req.Headers.Add(headerKey + ":" + header[headerKey]);
//}
}
byte[] data = Encoding.UTF8.GetBytes(body);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = Encoding.UTF8;
StreamReader reader = new StreamReader(stream, encode);
string content = reader.ReadToEnd();
stream.Close();
reader.Close();
return content;
}
/// <summary>
/// 远程证书验证
/// </summary>
/// <param name="sender"></param>
/// <param name="cert"></param>
/// <param name="chain"></param>
/// <param name="error"></param>
/// <returns>验证是否通过,始终通过</returns>
private static bool remoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain,
SslPolicyErrors error)
{
return true;
}
private static void initRequest(Dictionary<string, string> header, string url, string body, bool isPost)
{
// Accept
// string accept = "application/json"; // "*/*";
string accept = "*/*"; // "*/*";
header.Add("Accept", accept);
// ContentType
string contentType = "application/json";
header.Add("Content-Type", contentType);
//// appId
//header.Add("USER_KEY", _appkey);
//// appId
//header.Add("USER_SECRET", _secret);
//var timestamp = DateTime.Now.DateToTimeStamp();
//// build string to sign
//string signedStr = MD5Helper.Md5EncryptLowerCase(timestamp + _secret);
//// timestamp
//header.Add("timestamp", DateTime.Now.DateToTimeStamp());
//// sign
//header.Add("sign", signedStr);
if (_isHttps)
{
// set remote certificate Validation auto pass
ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidate);
// FIX修复不同.Net版对一些SecurityProtocolType枚举支持情况不一致导致编译失败等问题这里统一使用数值
// ServicePointManager.SecurityProtocol = (SecurityProtocolType)48 | (SecurityProtocolType)3072 |
// (SecurityProtocolType)768 | (SecurityProtocolType)192 ;
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
}
}
}