using MyCode.Project.Infrastructure.Common; using NPOI.POIFS.FileSystem; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace MyCode.Project.Infrastructure.JackYun { /// /// http 接口类 /// public class JackyunOpenHttpUtils { # region 变量 /// /// 并发控制锁对象 /// private static readonly Object __LOCK__ = new Object(); /// /// 在吉客云开放平台上申请的Appekey /// private const string APPKEY = "71030238";//"21578653"; /// /// 在吉客云开放平台上申请的AppeSecret /// private const string APPSECRET = "0fbe36cc4308405cacadf516338be4c8";// "d6ea919cb75a44879fcdbea211066b9c"; /// /// /// private const string Token = "c5cd87bb574483e8dd6acbf72f577fe0"; /// /// 吉客云开放平台网关 /// private const string GATEWAY = "https://open.jackyun.com/open/openapi/do"; //private const string GATEWAY = "http://localhost:9090/open/openapi/do"; #endregion #region 供外部调用的 请求开放平台的http Post方法 /// /// 请求开放平台的Post方法 /// /// 方法名 /// 版本号 /// 业务参数信息 /// public static string Post(string method, string version, BaseRequestBizData bizData) { // 构造请求参数(name1=value1&name2=value2格式)。 var dic = new SortedDictionary(); dic.Add("method", method); dic.Add("appkey", APPKEY); dic.Add("version", version); dic.Add("contenttype", "json"); dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); dic.Add("bizcontent", JsonHelper.ToJson(bizData)); // 构建待签名的字符串。 StringBuilder sbSignData = new StringBuilder(APPSECRET); foreach (var entry in dic) { sbSignData.Append(entry.Key + entry.Value); } sbSignData.Append(APPSECRET); string signStr = sbSignData.ToString().ToLower(); // 生成签名。 dic.Add("sign", MakeMD5(sbSignData.ToString().ToLower(), Encoding.UTF8)); //构造请求参数(name1=value1&name2=value2格式) StringBuilder sbPostData = new StringBuilder(); foreach (var entry in dic) { sbPostData.Append("&").Append(entry.Key).Append("=").Append(entry.Value); } sbPostData.Append("&").Append("token").Append("=").Append(Token); string postDataStr = sbPostData.ToString().Substring(1); LogHelper.Info("postDataStr:"+postDataStr); return postData(GATEWAY, postDataStr); } #endregion #region MD5方法 /// /// 生成MD5码。 /// /// 待生成字符串 /// 编码格式 /// public static string MakeMD5(string original, Encoding encoding) { var hashmd5 = new MD5CryptoServiceProvider(); byte[] byteOriginal = hashmd5.ComputeHash(encoding.GetBytes(original)); StringBuilder ciphertext = new StringBuilder(32); for (int i = 0; i < byteOriginal.Length; i++) { ciphertext.Append(byteOriginal[i].ToString("x").PadLeft(2, '0')); } return ciphertext.ToString(); } #endregion #region http 相关方法 #region http post 请求方法 /// /// http post 请求方法。 /// /// 路径 /// 发送的数据(name1=value1&name2=value2)格式 /// HTTP-Post返回结果 public static string postData(string url, string data) { return postData(url, data, Encoding.UTF8, 300000); } public static string postData(string url, string postData, Encoding encoding, int timeOut) { string method = "POST"; return Request(url, postData, method, null, null, null, timeOut, null, encoding, null); } /// /// 通用请求。 /// /// 地址 /// 请求数据(当为GET时,自动追加到url中) /// 请求方式 /// Accept 标识 /// ContentType标识 /// Host 标识 /// 超时时间 /// 请求头部文件 /// 安全协议 /// 字符编码 /// http请求结果 public static string Request(string url, string postData, string method, string accept, string contentType, string host, int timeout, NameValueCollection headers, Encoding en, SecurityProtocolType? spType) { //字符编码。 if (null == en) en = Encoding.UTF8; //超时时间。 if (timeout <= 0) timeout = 60000; //自动拼接GET请求的URL。 if (method.ToUpper().Equals("GET") && !string.IsNullOrEmpty(postData)) { if (url.IndexOf("?") > 0) url += "&" + postData; else url += "?" + postData; } //创建请求。 var request = CreateHttpWebRequest(url, method, accept, contentType, host, timeout, headers, en, spType); //如果是非GET,加入POST数据流。 if (!method.ToUpper().Equals("GET") && !string.IsNullOrEmpty(postData)) WriteBytes(request, postData, en); return ResponseString(request, en); } #endregion #region 创建HttpWebRequest对象 /// /// 创建HttpWebRequest对象。 /// /// 地址 /// 请求方式(Post Get Put Delete) /// Accept 标识 /// ContentType 标识 /// Host 标识 /// 超时时间 /// 请求头部参数 /// 安全协议标识 /// HttpWebRequest public static HttpWebRequest CreateHttpWebRequest(string url, string method, string accept, string contentType, string host, int timeout, NameValueCollection headers, Encoding en, SecurityProtocolType? spType) { var request = WebRequest.Create(url) as HttpWebRequest; request.KeepAlive = false; request.AllowAutoRedirect = true; request.Timeout = timeout; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0"; //请求方式 默认为Post if (string.IsNullOrEmpty(method)) method = "Post"; request.Method = method; //Accept 标识 默认text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 if (string.IsNullOrEmpty(accept)) accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.Accept = accept; //ContentType 标识 默认"application/x-www-form-urlencoded; charset=" + this.Encode.WebName if (string.IsNullOrEmpty(contentType)) contentType = "application/x-www-form-urlencoded; charset=" + en.WebName; request.ContentType = contentType; ///Host 标识 if (!string.IsNullOrEmpty(host)) request.Host = host; //头部文件 if (headers != null) { foreach (string item in headers.Keys) { //特殊处理,前端将Content-Type加到requestHeaders中,这里进行处理。 if (string.Equals(item, "Content-Type", StringComparison.CurrentCultureIgnoreCase)) { request.ContentType = headers[item]; continue; } else if (string.Equals(item, "Host", StringComparison.CurrentCultureIgnoreCase)) { request.Host = headers[item]; continue; } else if (string.Equals(item, "ProtocolVersion", StringComparison.CurrentCultureIgnoreCase)) { request.ProtocolVersion = string.Equals("Version10", headers[item], StringComparison.CurrentCultureIgnoreCase) ? HttpVersion.Version10 : HttpVersion.Version11; continue; } request.Headers[item] = headers[item]; } } //Https安全协议 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { if (spType != null) ServicePointManager.SecurityProtocol = spType.Value; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; }); request.Credentials = CredentialCache.DefaultCredentials; } return request; } #endregion #region 写入POST请求字节流 /// /// 写入POST请求字节流。 /// /// http请求 /// 请求参数 /// 字符编码 private static void WriteBytes(HttpWebRequest request, string postData, Encoding en) { if (null == postData) return; var buffer = en.GetBytes(postData); request.ContentLength = buffer.Length; using (var reqStream = request.GetRequestStream()) { reqStream.Write(buffer, 0, buffer.Length); } } #endregion #region 输出字符串 /// /// 输出字符串。 /// /// HttpWebRequest /// 字符编码 /// 输出字节流 private static string ResponseString(HttpWebRequest request, Encoding en) { using (var res = GetResponse(request)) { if (null == en || en == Encoding.UTF32) en = Encoding.GetEncoding(res.CharacterSet); using (Stream resStream = res.GetResponseStream()) { using (var sr = new StreamReader(resStream, en)) { return sr.ReadToEnd(); } } } } #endregion #region 获取网络资源 /// /// 获取网络资源的响应。 /// /// http请求对象 /// private static HttpWebResponse GetResponse(HttpWebRequest request) { try { return (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { var res = (HttpWebResponse)ex.Response; if (res == null) throw; return res; } } #endregion #endregion } }