using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace HDLMonitorService.Helper
{
public class HttpHp
{
///
/// 发送POST请求
///
///
///
///
///
public static T Post(string url, string reqDataStr) where T : class
{
return HttpRequet(url, reqDataStr, "POST", "application/json;charset=UTF-8");
}
///
/// 发送HTTP请求
///
///
///
///
///
///
public static T HttpRequet(string url, string reqDataStr, string Method, string contentType) where T : class
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = Method;
request.ContentType = contentType;
request.ContentLength = 0;
if (reqDataStr != null)
{
var reqData = Encoding.UTF8.GetBytes(reqDataStr);
request.ContentLength = reqData.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(reqData, 0, reqData.Length);
}
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return JsonConvert.DeserializeObject(responseString);
}
///
/// 2020-11-02
/// 基础服务的接口都要校验sign
/// 计算sign签名
///
///
public static string GetSignRequestJson(object requestObj, Dictionary paramDictionary = null)
{
try
{
//1. 将model实体转为Dictionary
if (paramDictionary == null)
{
paramDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject>(Newtonsoft.Json.JsonConvert.SerializeObject(requestObj));
}
//2. 计算sign
if (paramDictionary != null)
{
paramDictionary.Add("appKey", ConfigurationManager.AppSettings["AppKey"].ToString());
paramDictionary.Add("timestamp", GetTimestamp());
//2.1 字典升序
paramDictionary = paramDictionary.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
//2.2 拼接按URL键值对
string str = string.Empty;
foreach (KeyValuePair item in paramDictionary)
{
//Value为null不参加校验
if (item.Value != null)
{
//Value.ToString()为null或者""也不参加校验
//if (!string.IsNullOrEmpty(item.Value.ToString()) && (item.Value is string || item.Value.GetType().IsValueType))
//{
//检测当前参数是否需要参与校验
if (IfValueNeedSign(item.Value.ToString()))
{
//如果是bool类型,要转小写
if (item.Value is bool)
{
str += item.Key + "=" + item.Value.ToString().ToLower() + "&";
}
else
{
str += item.Key + "=" + item.Value.ToString() + "&";
}
}
}
}
//2.3 拼接SECRET_KEY
str = str.Substring(0, str.Length - 1) + ConfigurationManager.AppSettings["SecretKey"].ToString();
//2.4 MD5转换+转小写
var signstr = SignMD5Encrypt(str);
paramDictionary.Add("sign", signstr);
var signResult = Newtonsoft.Json.JsonConvert.SerializeObject(paramDictionary);
return signResult;
}
else
{
return "";
}
}
catch
{
return "";
}
}
///
/// 判断当前值是否需要参与签名,保持跟云端一致
/// 空字符串不参与
/// 数组,集合,对象不参与
///
///
///
static bool IfValueNeedSign(string valueStr)
{
if (string.IsNullOrEmpty(valueStr) || valueStr.StartsWith("{") || valueStr.StartsWith("["))
{
return false;
}
return true;
}
static long GetTimestamp()
{
return (long)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
}
static string SignMD5Encrypt(string str)
{
byte[] result = Encoding.UTF8.GetBytes(str.Trim()); //tbPass为输入密码的文本框
var md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
string passwordMD5 = BitConverter.ToString(output).Replace("-", string.Empty); //tbMd5pass为输出加密文本的文本框
return passwordMD5.Trim().ToLower();
}
}
}