using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using HDL_ON.Entity;
using RestSharp;
using Shared;
namespace HDL_ON.DAL.Server
{
public class HttpUtil
{
#region HttpUtil 全局常量
/////
///// API_HTTPS
/////
//public const string API_HTTPS = "https://";
///
/// RegionMark
///
public const string RegionMark = "HDL";
///
/// 请求超时时间
///
public const int TIME_OUT = 10;
///
/// 特殊接口请求超时时间
///
public const int TIME_OUT_LONG = 20;
///////
/////// Bearer 暂时设为空,从登陆成功的返回的headerPrefix参数动态获取
///////
//public const string TOKEN_BEARER = "Bearer ";
#endregion
///
/// 固定域名
///
//public const string GlobalRequestHttpsHost = "https://center.hdlcontrol.com";
public const string GlobalRequestHttpsHost = "https://test-gz.hdlcontrol.com";
///
/// Get 请求服务器方法
///
///
///
///
///
///
///
///
public static ResponsePackNew RequestHttpsGet(string apiPath, Dictionary queryDictionary = null, Dictionary urlSegmentDictionary = null, string urlHead = "", string replaceToken = "", int mTimeout = 10)
{
return RequestHttps(Method.GET, apiPath, null, queryDictionary, urlSegmentDictionary, urlHead, replaceToken, mTimeout);
}
/////
///// 通用 请求服务器方法
/////
///// 请求类型
/////
/////
/////
/////
/////
///// 请求超时时间,默认10
/////
/////
//public static ResponsePackNew RequestHttpsBase(Method method, string apiPath, string bodyParameterJson = null, Dictionary queryDictionary = null, Dictionary urlSegmentDictionary = null, string urlHead = "", string replaceToken = "", int mTimeout = 10, bool needErrorTip = true)
//{
// var mResponsePackNew = RequestHttps(method, apiPath, bodyParameterJson, queryDictionary, urlSegmentDictionary, urlHead, replaceToken, mTimeout);
// if (needErrorTip)
// {
// if (mResponsePackNew.Code.ToUpper() != SUCCESS_CODE)
// {
// IMessageCommon.Current.ShowErrorInfoAlter(apiPath, mResponsePackNew.Code);
// }
// }
// return mResponsePackNew;
//}
///
/// POST请求方法 body参数
/// 针对住宅相关接口封装
/// 调用住宅当前所在区域域名
/// 如果是分享住宅,使用主人的token进行相关操作
///
///
///
///
///
public static ResponsePackNew RequestHttpsPostFroHome(string apiPath, string bodyParameterJson, int mTimeout = 10)
{
string urlHead = DB_ResidenceData.residenceData.residecenInfo.regionUrl;
var replaceToken = "";
if (DB_ResidenceData.residenceData.residecenInfo.IsOthreShare)
{
replaceToken = DB_ResidenceData.residenceData.MasterToken;
}
return RequestHttps(Method.POST, apiPath, bodyParameterJson, null, null, urlHead, replaceToken, mTimeout);
}
///
/// POST请求方法 body参数
///
///
///
///
///
///
///
///
public static ResponsePackNew RequestHttpsPost(string apiPath, string bodyParameterJson, string urlHead = "", string replaceToken = "", int mTimeout = 10)
{
return RequestHttps(Method.POST, apiPath, bodyParameterJson, null, null, urlHead, replaceToken, mTimeout);
}
///
/// POST请求方法 queryDictionary
///
///
///
///
///
///
///
///
public static ResponsePackNew RequestHttpsPost(string apiPath, Dictionary queryDictionary, string urlHead = "", string replaceToken = "", int mTimeout = 10)
{
return RequestHttps(Method.POST, apiPath, null, queryDictionary, null, urlHead, replaceToken, mTimeout);
}
///
/// 通用 请求服务器方法
///
///
///
///
///
///
///
///
///
///
public static ResponsePackNew RequestHttps(Method method, string apiPath, string bodyParameterJson = null, Dictionary queryDictionary = null, Dictionary urlSegmentDictionary = null, string urlHead = "", string replaceToken = "", int mTimeout = 10)
{
#region HttpWebRequest
try
{
//if (string.IsNullOrEmpty(urlHead))
//{
// urlHead = UserInfo.Current.RequestHttpsHost;
//}
//string requestFullUrl = urlHead + apiPath;
//**************测试**************
string requestFullUrl = GlobalRequestHttpsHost + apiPath;
//**************测试**************
RestClient client = new RestClient(requestFullUrl);
RestRequest request = new RestRequest(method);
request.Timeout = mTimeout * 1000;
request.AddHeader("content-type", "application/json");
//request.AddHeader ("cache-control", "no-cache");
if (string.IsNullOrEmpty(replaceToken))
{
if(UserInfo.Current != null)
{/* 如果不需要验证Token可以不用传入 */
request.AddHeader("Authorization", UserInfo.Current.LoginTokenString);
}
}
else
{
request.AddHeader("Authorization", replaceToken);
}
if (bodyParameterJson != null)
{
request.AddParameter("application/json", bodyParameterJson, ParameterType.RequestBody);
}
if (queryDictionary != null)
{
foreach (var data in queryDictionary)
{
request.AddQueryParameter(data.Key, data.Value.ToString());
}
}
if (urlSegmentDictionary != null)
{
foreach (var data in urlSegmentDictionary)
{
request.AddUrlSegment(data.Key, data.Value.ToString());
}
}
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
ResponsePackNew revertObj = new ResponsePackNew() { };
revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content);
//*****一些判空处理*****************
if (revertObj.Code == null)
{
revertObj.Code = "DATA_EXCEPTION";
}
if (revertObj.Data == null)
{
revertObj.Data = "";
}
//*****一些判空处理*****************
////统一转成大写
//revertObj.StateCode = revertObj.StateCode.ToUpper ();
return revertObj;
}
catch (Exception ex)
{
HDL_ON.Utlis.WriteLine(ex.Message);
return new ResponsePackNew() { Code = "DATA_EXCEPTION" };
}
}
else
{
HDL_ON.Utlis.WriteLine(response.Content);
return new ResponsePackNew() { Code = "NETWORK_ERROR" };
}
}
catch (Exception ex)
{
HDL_ON.Utlis.WriteLine(ex.Message);
return new ResponsePackNew() { Code = "NETWORK_ERROR" };
}
#endregion
}
///
/// 下载文件 请求服务器方法
///
///
///
///
///
///
///
///
public static byte[] RequestHttpsDownload(string apiPath, string bodyParameterJson = null, Dictionary queryDictionary = null, string urlHead = "", string replaceToken = "", int mTimeout = 20)
{
#region RestRequest
try
{
//if (string.IsNullOrEmpty (urlHead)) {
// urlHead = UserInfo.Current.RequestHttpsHost;
//}
//string requestFullUrl = urlHead + apiPath;
//**************测试**************
string requestFullUrl = GlobalRequestHttpsHost + apiPath;
//**************测试**************
RestClient client = new RestClient(requestFullUrl);
//client.Timeout = mTimeout * 1000;
RestRequest request = new RestRequest(Method.POST);
request.Timeout = mTimeout * 1000;
request.AddHeader("content-type", "application/json");
if (string.IsNullOrEmpty(replaceToken))
{
if ( UserInfo.Current != null)
{/* 如果不需要验证Token可以不用传入 */
request.AddHeader("Authorization", UserInfo.Current.LoginTokenString);
}
}
else
{
request.AddHeader("Authorization", replaceToken);
}
if (bodyParameterJson != null)
{
request.AddParameter("application/json", bodyParameterJson, ParameterType.RequestBody);
}
if (queryDictionary != null)
{
foreach (var data in queryDictionary)
{
request.AddQueryParameter(data.Key, data.Value.ToString());
}
}
IRestResponse response = client.Execute(request);
return response.RawBytes;
}
catch (Exception ex)
{
HDL_ON.Utlis.WriteLine(ex.Message);
return null;
}
#endregion
}
///
/// 上传 请求服务器方法
///
///
///
///
///
///
///
///
///
///
public static ResponsePackNew RequestHttpsUpload(Method method, string apiPath, object bodyParameterObject = null, Dictionary queryDictionary = null, Dictionary urlSegmentDictionary = null, string urlHead = "", string replaceToken = "", int mTimeout = 10)
{
#region HttpWebRequest
try
{
//if (string.IsNullOrEmpty (urlHead)) {
// urlHead = UserInfo.Current.RequestHttpsHost;
//}
//string requestFullUrl = urlHead + apiPath;
//**************测试**************
string requestFullUrl = GlobalRequestHttpsHost + apiPath;
//**************测试**************
RestClient client = new RestClient(requestFullUrl);
//client.Timeout = mTimeout * 1000;
RestRequest request = new RestRequest(method);
request.Timeout = mTimeout * 1000;
//request.AddHeader ("content-type", "application/json");
request.AddHeader("content-type", "application/octet-stream");
if (string.IsNullOrEmpty(replaceToken))
{
if ( UserInfo.Current != null)
{/* 如果不需要验证Token可以不用传入 */
request.AddHeader("Authorization", UserInfo.Current.LoginTokenString);
}
}
else
{
request.AddHeader("Authorization", replaceToken);
}
if (bodyParameterObject != null)
{
request.AddParameter("application/octet-stream", bodyParameterObject, ParameterType.RequestBody);
}
if (queryDictionary != null)
{
foreach (var data in queryDictionary)
{
request.AddQueryParameter(data.Key, data.Value.ToString());
}
}
if (urlSegmentDictionary != null)
{
foreach (var data in urlSegmentDictionary)
{
request.AddUrlSegment(data.Key, data.Value.ToString());
}
}
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
ResponsePackNew revertObj = new ResponsePackNew() { };
revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content);
if (revertObj.Code == null)
{
revertObj.Code = "DATA_EXCEPTION";
}
////统一转成大写
//revertObj.StateCode = revertObj.StateCode.ToUpper ();
return revertObj;
}
catch (Exception ex)
{
HDL_ON.Utlis.WriteLine(ex.Message);
return new ResponsePackNew() { Code = "DATA_EXCEPTION" };
}
}
else
{
HDL_ON.Utlis.WriteLine(response.Content);
return new ResponsePackNew() { Code = "NETWORK_ERROR" };
}
}
catch (Exception ex)
{
HDL_ON.Utlis.WriteLine(ex.Message);
return new ResponsePackNew() { Code = "NETWORK_ERROR" };
}
#endregion
}
///
///
///
const string APP_KEY = "HDL-HOME-APP-TEST";
///
///
///
const string SECRET_KEY = "WeJ8TY88vbakCcnvH8G1tDUqzLWY8yss";
///
/// 获取当前时间戳值
///
///
static string GetTimestamp()
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
return ((long)(DateTime.Now - startTime).TotalSeconds).ToString(); // 相差秒数
}
///
///
///
///
///
static string SignMD5Encrypt(string s)
{
byte[] sign = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(s));
string signstr = string.Empty;
foreach (byte item in sign)
{
signstr += item.ToString("X2");
}
return signstr.ToLower();
}
///
/// 2020-11-02
/// 基础服务的接口都要校验sign
/// 计算sign签名
///
///
public static string GetSignRequestJson(object requestObj)
{
try
{
//1. 将model实体转为Dictionary
var paramDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject>(Newtonsoft.Json.JsonConvert.SerializeObject(requestObj));
//2. 计算sign
if (paramDictionary != null)
{
paramDictionary.Add("appKey", APP_KEY);
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()))
{
//如果是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) + SECRET_KEY;
//2.4 MD5转换+转小写
var signstr = SignMD5Encrypt(str);
paramDictionary.Add("sign", signstr);
return Newtonsoft.Json.JsonConvert.SerializeObject(paramDictionary);
}
else
{
return "";
}
}
catch
{
return "";
}
}
}
///
/// 响应参数
///
[Serializable]
public class ResponsePackNew
{
///
/// 响应状态码
///
public string Code;
///
/// 响应内容
///
public object Data;
///
/// 响应错误信息
///
public string message;
/////
///// isSuccess
/////
//public bool isSuccess;
/////
///// timestamp
/////
//public string timestamp;
}
}