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

241 lines
10 KiB

3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Net;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Net.Http.Headers;
  12. namespace ICSSoft.FromERP
  13. {
  14. public class HttpHelper
  15. {
  16. /// <summary>
  17. /// POST请求
  18. /// </summary>
  19. /// <param name="url">地址</param>
  20. /// <param name="requestJson">请求json</param>
  21. /// <param name="token">token</param>
  22. /// <returns></returns>
  23. public static async Task<T> HttpClientPost<T>(string url, string requestJson, Dictionary<string, string> dic=null , string contentType = "application/json", string token = "") where T : new()
  24. {
  25. string result = string.Empty;
  26. Uri postUrl = new Uri(url);
  27. using (HttpContent httpContent = new StringContent(requestJson, System.Text.Encoding.UTF8, contentType))
  28. {
  29. //使用注入的httpclientfactory获取client
  30. using (var httpClient = new HttpClient( ))
  31. {
  32. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  33. {
  34. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
  35. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  36. // httpClient.BaseAddress. = HttpVersion.Version10;
  37. // httpClient.DefaultRequestVersion = HttpVersion.Version30,
  38. }
  39. //设置请求头
  40. //设置超时时间
  41. if (!string.IsNullOrEmpty(token))
  42. httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  43. if (dic != null)
  44. {
  45. foreach (var item in dic)
  46. {
  47. httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
  48. }
  49. }
  50. httpClient.Timeout = new TimeSpan(0, 0, 60);
  51. HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
  52. res.EnsureSuccessStatusCode();
  53. result = res.Content.ReadAsStringAsync().Result;
  54. return JsonConvert.DeserializeObject<T>(result);
  55. }
  56. }
  57. }
  58. public static async Task<T> HttpClientPost2<T>(string url, string requestJson, Dictionary<string, string> dic, string contentType = "application/json") where T : new()
  59. {
  60. string result = string.Empty;
  61. Uri postUrl = new Uri(url);
  62. //使用注入的httpclientfactory获取client
  63. using (var httpClient = new HttpClient())
  64. {
  65. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
  66. using (StringContent strcontent = new StringContent(requestJson, Encoding.UTF8, contentType))
  67. {
  68. var message = new HttpRequestMessage(HttpMethod.Post, url);
  69. //设置cookie信息
  70. foreach (var item in dic)
  71. {
  72. message.Headers.Add(item.Key, item.Value);
  73. }
  74. //设置contetn
  75. message.Content = strcontent;
  76. //发送请求
  77. var res = httpClient.SendAsync(message).Result;
  78. res.EnsureSuccessStatusCode();
  79. result = await res.Content.ReadAsStringAsync();
  80. return JsonConvert.DeserializeObject<T>(result);
  81. }
  82. ////设置请求头
  83. ////设置超时时间
  84. //if (dic != null && dic.Count > 0)
  85. //{
  86. // foreach (var item in dic)
  87. // {
  88. // httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
  89. // }
  90. //}
  91. ////if (!string.IsNullOrEmpty(token))
  92. //// httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  93. //httpClient.Timeout = new TimeSpan(0, 0, 60);
  94. //HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
  95. //res.EnsureSuccessStatusCode();
  96. //result = await res.Content.ReadAsStringAsync();
  97. //return JsonConvert.DeserializeObject<T>(result);
  98. }
  99. }
  100. public static async Task<T> HttpClientGet<T>(string url, string contentType = "application/json", string token = "") where T : new()
  101. {
  102. using (HttpClient httpClient = new HttpClient())
  103. {
  104. if (!string.IsNullOrEmpty(token))
  105. httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  106. httpClient.Timeout = new TimeSpan(0, 0, 60);
  107. HttpResponseMessage res = httpClient.GetAsync(url).Result;
  108. res.EnsureSuccessStatusCode();
  109. var t = res.Content.ReadAsStringAsync().Result;
  110. return JsonConvert.DeserializeObject<T>(t);
  111. };
  112. }
  113. public static async Task<T> PostForm<T, R>(string Url, R message, Dictionary<string, string> dic=null) where T : new()
  114. {
  115. var res = new T();
  116. using (HttpClient httpClient = new HttpClient())
  117. {
  118. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
  119. var body = new List<KeyValuePair<string, string>>();
  120. foreach (PropertyInfo info in typeof(R).GetProperties())
  121. {
  122. var entity = new KeyValuePair<string, string>(info.Name, info.GetValue(message).ToString());
  123. body.Add(entity);
  124. }
  125. var content = new FormUrlEncodedContent(body);
  126. httpClient.DefaultRequestHeaders.Add("Method", "Post");
  127. if (dic != null)
  128. {
  129. foreach (var item in dic)
  130. {
  131. httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
  132. }
  133. }
  134. HttpResponseMessage response = httpClient.PostAsync(Url, content).Result;
  135. if ((int)response.StatusCode == 200)
  136. {
  137. response.EnsureSuccessStatusCode();
  138. }
  139. string result = response.Content.ReadAsStringAsync().Result;
  140. res = JsonConvert.DeserializeObject<T>(result);
  141. }
  142. return res;
  143. }
  144. public static async Task<T> HttpPostNoFile<T>(string url, string data)
  145. {
  146. // Encoding encoding = Encoding.UTF8;
  147. // string jsonParam = data;
  148. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  149. request.Method = "post";
  150. request.ContentType = "application/json";
  151. byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
  152. request.ContentLength = byteData.Length;
  153. using (Stream postStream = request.GetRequestStream())
  154. {
  155. postStream.Write(byteData, 0, byteData.Length);
  156. }
  157. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  158. {
  159. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  160. {
  161. var result= reader.ReadToEnd().ToString();
  162. return JsonConvert.DeserializeObject<T>(result);
  163. }
  164. }
  165. }
  166. public static string PostData(byte[] data, string url, string contentType = "application/json", int timeout = 20)
  167. {
  168. //创建httpWebRequest对象
  169. HttpWebRequest httpRequest = null;
  170. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  171. {
  172. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
  173. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  174. httpRequest = WebRequest.Create(url) as HttpWebRequest;
  175. httpRequest.ProtocolVersion = HttpVersion.Version10;
  176. }
  177. else
  178. {
  179. httpRequest = WebRequest.Create(url) as HttpWebRequest;
  180. }
  181. if (httpRequest == null)
  182. {
  183. throw new ApplicationException(string.Format("Invalid url string: {0}", url));
  184. }
  185. //填充httpWebRequest的基本信息
  186. httpRequest.ContentType = contentType;
  187. httpRequest.Method = "POST";
  188. httpRequest.Timeout = timeout * 1000;
  189. //填充并发送要post的内容
  190. httpRequest.ContentLength = data.Length;
  191. httpRequest.Headers.Add("deipaaskeyauth", "a5P1RTL4380zd9jpb57qXx63rdynUHN2");
  192. using (Stream requestStream = httpRequest.GetRequestStream())
  193. {
  194. requestStream.Write(data, 0, data.Length);
  195. requestStream.Close();
  196. }
  197. //发送post请求到服务器并读取服务器返回信息
  198. var response = httpRequest.GetResponse();
  199. using (Stream responseStream = response.GetResponseStream())
  200. {
  201. //读取服务器返回信息
  202. string stringResponse = string.Empty;
  203. using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
  204. {
  205. stringResponse = responseReader.ReadToEnd();
  206. }
  207. responseStream.Close();
  208. return stringResponse;
  209. }
  210. }
  211. }
  212. }