using JSMachine.DCS.Infrastructure; using Microsoft.AspNetCore.Mvc.ViewFeatures; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Web; namespace JSMachine.WMS.Infrastructure.Helper { public static class HttpRequestHelper { /// /// 字典方式请求,支持表单数据 /// /// /// /// /// /// /// public async static Task RequestByDic(string url, Method method, Dictionary dic = null, List postFileParam = null, int timeOut = 5000) { RestClient client = new(url) { Timeout = timeOut }; RestRequest request = new(method); dic?.Select(p => p.Key) .ToList() .ForEach(key => request.AddParameter(key, dic[key])); postFileParam?.ForEach(p => { request.AddFile(p.RemoteParamName, p.FileBytes, p.FileName); }); IRestResponse response = await client.ExecuteAsync(request); if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) return response.Content; if (response.ErrorException != null) { LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}"); LogHelper.Error("当前请求url:" + url); } return null; } /// /// JSON参数请求 /// /// /// /// /// /// public async static Task RequestByJson(string url, Method method, string json, int timeOut = 5000) { RestClient client = new(url) { Timeout = timeOut }; RestRequest request = new(method); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", json, ParameterType.RequestBody); IRestResponse response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) return response.Content; if (response.ErrorException != null) { LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}"); LogHelper.Error("当前请求url:" + url); } return null; } /// /// JSON参数请求 /// /// /// /// /// /// /// public async static Task RequestByJson(string url, Method method, string json, string token, int timeOut = 5000) { RestClient client = new(url) { Timeout = timeOut }; RestRequest request = new(method); request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", json, ParameterType.RequestBody); IRestResponse response = await client.ExecuteAsync(request); if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) return response.Content; if (response.ErrorException != null) { LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}"); LogHelper.Error("当前请求url:" + url); } return null; } /// /// 无参请求返回二进制(用于下载文件) /// /// /// /// /// public async static Task RequestRturnRawAsync(string url, Method method, int timeOut = 5000) { if (string.IsNullOrEmpty(url)) return null; RestClient client = new(url) { Timeout = timeOut }; RestRequest request = new(method); request.AlwaysMultipartFormData = true; IRestResponse response = await client.ExecuteAsync(request); if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) return response.RawBytes; if (response.ErrorException != null) { LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}"); LogHelper.Error("当前请求url:" + url); } return null; } /// /// 无参请求返回二进制(用于下载文件) /// /// /// /// /// public static byte[] RequestRturnRaw(string url, Method method, int timeOut = 5000) { if (string.IsNullOrEmpty(url)) return null; RestClient client = new(url) { Timeout = timeOut }; RestRequest request = new(method); request.AlwaysMultipartFormData = true; IRestResponse response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) return response.RawBytes; if (response.ErrorException != null) { LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}"); LogHelper.Error("当前请求url:" + url); } return null; } /// /// 获取请求的数据 /// private static string GetResponseString(WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { if (stream == null) return string.Empty; using (var reader = new StreamReader(stream, Encoding.UTF8)) { return reader.ReadToEnd(); } } } /// /// 以GET方式请求HTTP地址并获取返回 /// public async static Task Get(string url, Dictionary headers = null, CookieCollection cookies = null) { HttpWebRequest request = null; WebResponse response = null; try { ServicePointManager.DefaultConnectionLimit = 200; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { //对服务端证书进行有效性校验 ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult; } request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; if (headers != null && headers.Count > 0) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } response = request.GetResponse(); return GetResponseString(response); } catch (System.Threading.ThreadAbortException e) { System.Threading.Thread.ResetAbort(); throw new Exception(e.Message); } finally { request?.Abort(); response?.Dispose(); } } /// /// 以POST方式请求HTTP地址并获取返回 /// /// HTTP地址 /// POST的键值对参数 /// /// /// public async static Task Post(string url, Dictionary parameters, Dictionary headers = null, CookieCollection cookies = null) { return await Post(url, GetPostData(parameters), null, headers, cookies); } /// /// 以POST方式请求HTTP地址并获取返回 /// /// HTTP地址 /// POST的内容 /// /// /// /// public async static Task Post(string url, string content, string contentType = null, Dictionary headers = null, CookieCollection cookies = null) { HttpWebRequest request = null; HttpWebResponse response = null; try { ServicePointManager.DefaultConnectionLimit = 200; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { //对服务端证书进行有效性校验 ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult; } request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = 30000; request.ContentType = contentType ?? "application/x-www-form-urlencoded"; if (headers != null && headers.Count > 0) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //发送POST数据 var data = Encoding.UTF8.GetBytes(content ?? string.Empty); request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } response = (HttpWebResponse)request.GetResponse(); return GetResponseString(response); } catch (System.Threading.ThreadAbortException e) { System.Threading.Thread.ResetAbort(); throw new Exception(e.Message); } catch (Exception e) { throw new Exception(e.Message); } finally { request?.Abort(); response?.Dispose(); } } /// /// 字典转化为post数据 /// /// /// private static string GetPostData(Dictionary dictionary) { if (dictionary == null || dictionary.Count == 0) return string.Empty; var sb = new StringBuilder(); var keys = dictionary.Keys.ToList(); for (var i = 0; i < keys.Count; i++) { if (i > 0) { sb.Append("&"); } sb.AppendFormat("{0}={1}", keys[i], HttpUtility.UrlEncode(dictionary[keys[i]])); } return sb.ToString(); } /// /// 验证证书 /// private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } } public class PostFileParam { public string RemoteParamName { get; set; } public string FileName { get; set; } public byte[] FileBytes { get; set; } } }