WEBHelper.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Text.Json.Serialization;
  9. using System.Threading.Tasks;
  10. namespace NEIntelligentControl2.Models.Messages
  11. {
  12. /// <summary>
  13. /// 用于进行WEB请求
  14. /// </summary>
  15. public class WEBHelper
  16. {
  17. /// <summary>
  18. /// 全局JSON配置
  19. /// </summary>
  20. private readonly JsonSerializerOptions _jso = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, IgnoreNullValues = true };
  21. /// <summary>
  22. /// 凭据
  23. /// </summary>
  24. public string Token { get; set; }
  25. public WEBHelper()
  26. {
  27. _jso.Converters.Add(new DateTiemConverter());
  28. _jso.Converters.Add(new DoubleConverter());
  29. }
  30. /// <summary>
  31. /// 使用POST请求数据,无返回值,用于更新与添加,数据以JSON形式附加在Body中
  32. /// </summary>
  33. /// <param name="url">请求链接</param>
  34. /// <param name="jval">附加的数据</param>
  35. public T HttpPostBody<T>(string url, object jval)
  36. {
  37. HttpWebRequest request = WebRequest.CreateHttp(url);
  38. request.Method = "POST";
  39. request.ContentType = "application/json";// ;charset=utf-8 application/x-www-form-urlencoded
  40. request.Headers.Add("Authorization",Token);
  41. if (jval != null)
  42. {
  43. var vl = JsonSerializer.Serialize(jval, _jso);
  44. var vs = Encoding.Default.GetBytes(vl);
  45. using (Stream st = request.GetRequestStream())
  46. {
  47. st.Write(vs, 0, vs.Length);
  48. }
  49. }
  50. WebResponse res = request.GetResponse();
  51. T value = default;
  52. using (StreamReader reader = new StreamReader(res.GetResponseStream()))
  53. {
  54. var val = reader.ReadToEnd();
  55. #if(DEBUG)
  56. Console.WriteLine(val);
  57. #endif
  58. value = JsonSerializer.Deserialize<T>(val, _jso);
  59. }
  60. return value;
  61. }
  62. /// <summary>
  63. /// 异步使用POST请求数据,无返回值,用于更新与添加,数据以JSON形式附加在Body中
  64. /// </summary>
  65. /// <param name="url">请求链接</param>
  66. /// <param name="jval">附加的数据</param>
  67. public async Task<T> HttpPostBodyAsync<T>(string url, object jval)
  68. {
  69. return await Task.Run(() => HttpPostBody<T>(url, jval));
  70. }/// <summary>
  71. /// 使用POST请求数据,用于更新与添加,数据以JSON形式附加在Body中
  72. /// </summary>
  73. /// <param name="url">请求链接</param>
  74. /// <param name="jval">附加的数据</param>
  75. internal string HttpPostBodyString(string url, object jval)
  76. {
  77. HttpWebRequest request = WebRequest.CreateHttp(url);
  78. request.Method = "POST";
  79. request.ContentType = "application/json";// ;charset=utf-8 application/x-www-form-urlencoded
  80. request.Headers.Add("Authorization", Token);
  81. if (jval != null)
  82. {
  83. var vl = JsonSerializer.Serialize(jval, _jso);
  84. var vs = Encoding.Default.GetBytes(vl);
  85. using (Stream st = request.GetRequestStream())
  86. {
  87. st.Write(vs, 0, vs.Length);
  88. }
  89. }
  90. WebResponse res = request.GetResponse();
  91. using (StreamReader reader = new StreamReader(res.GetResponseStream()))
  92. {
  93. var val = reader.ReadToEnd();
  94. return val;
  95. }
  96. }
  97. /// <summary>
  98. /// 使用GET请求数据(只能请求返回值为JSON格式的数据)
  99. /// </summary>
  100. /// <typeparam name="T">得到的数据</typeparam>
  101. /// <param name="url">请求地址</param>
  102. /// <param name="y">请求参数</param>
  103. /// <returns>请求类型</returns>
  104. public T HttpGetJSON<T>(string url)
  105. {
  106. HttpWebRequest request = WebRequest.CreateHttp(url);
  107. request.Headers.Add("Authorization", Token);
  108. WebResponse res = request.GetResponse();
  109. string val = "";
  110. using (StreamReader reader = new StreamReader(res.GetResponseStream()))
  111. {
  112. val = reader.ReadToEnd();
  113. }
  114. request.Abort();
  115. var tt = JsonSerializer.Deserialize<T>(val, _jso);
  116. return tt;
  117. }
  118. /// <summary>
  119. /// 使用GET请求数据,获得请求字符串
  120. /// </summary>
  121. /// <typeparam name="T">得到的数据</typeparam>
  122. /// <param name="url">请求地址</param>
  123. /// <param name="y">请求参数</param>
  124. /// <returns>请求类型</returns>
  125. public string HttpGetString(string url)
  126. {
  127. HttpWebRequest request = WebRequest.CreateHttp(url);
  128. request.Headers.Add("Authorization", Token);
  129. WebResponse res = request.GetResponse();
  130. string val = "";
  131. using (StreamReader reader = new StreamReader(res.GetResponseStream()))
  132. {
  133. val = reader.ReadToEnd();
  134. }
  135. request.Abort();
  136. return val;
  137. }
  138. /// <summary>
  139. /// 使用GET请求数据,异步方法(只能请求返回值为JSON格式的数据)
  140. /// </summary>
  141. /// <typeparam name="T">得到的数据</typeparam>
  142. /// <param name="url">请求地址</param>
  143. /// <param name="y">请求参数</param>
  144. /// <returns>请求类型</returns>
  145. public async Task<T> HttpGetJSONAsync<T>(string url)
  146. {
  147. return await Task.Run(() =>
  148. {
  149. return HttpGetJSON<T>(url);
  150. });
  151. }
  152. /// <summary>
  153. /// 使用GET请求数据(只能请求返回值为JSON格式的数据)
  154. /// </summary>
  155. /// <typeparam name="T">得到的数据</typeparam>
  156. /// <param name="url">请求地址</param>
  157. /// <param name="y">请求参数</param>
  158. /// <returns>请求类型</returns>
  159. public string HttpGetString(string url, object args)
  160. {
  161. string arg = GetArgs(args);
  162. var ur = url + arg;
  163. HttpWebRequest request = WebRequest.CreateHttp(ur);
  164. WebResponse res = request.GetResponse();
  165. string val = "";
  166. using (StreamReader reader = new StreamReader(res.GetResponseStream()))
  167. {
  168. val = reader.ReadToEnd();
  169. }
  170. request.Abort();
  171. return val;
  172. }
  173. /// <summary>
  174. /// 将对象转换成请求字符串
  175. /// </summary>
  176. /// <param name="args">要转换的对象</param>
  177. /// <returns>转换后的字符串</returns>
  178. private string GetArgs(object args)
  179. {
  180. if (args == null) return "";
  181. StringBuilder sb = new StringBuilder();
  182. sb.Append("?");
  183. var tp = args.GetType();
  184. var pr = tp.GetProperties();
  185. bool isFirst = true;
  186. foreach (var v in pr)
  187. {
  188. var vv = v.GetValue(args)?.ToString();
  189. if (string.IsNullOrWhiteSpace(vv)) continue;
  190. if (!isFirst)
  191. {
  192. sb.Append("&");
  193. }
  194. sb.Append(v.Name).Append("=").Append(vv);
  195. isFirst = false;
  196. }
  197. return sb.ToString();
  198. }
  199. /// <summary>
  200. /// JSON编码
  201. /// </summary>
  202. public string Serialize(object obj)
  203. {
  204. return JsonSerializer.Serialize(obj, _jso);
  205. }
  206. /// <summary>
  207. /// JSON解码
  208. /// </summary>
  209. public T Deserialize<T>(string s)
  210. {
  211. return JsonSerializer.Deserialize<T>(s, _jso);
  212. }
  213. }
  214. /// <summary>
  215. /// JSON时间转换
  216. /// </summary>
  217. public class DateTiemConverter : JsonConverter<DateTime>
  218. {
  219. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  220. {
  221. DateTime.TryParse(reader.GetString(), out DateTime dt);
  222. return dt;
  223. }
  224. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  225. {
  226. writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
  227. }
  228. }
  229. /// <summary>
  230. /// JSON时间转换
  231. /// </summary>
  232. public class DoubleConverter : JsonConverter<double>
  233. {
  234. public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  235. {
  236. if(reader.TokenType== JsonTokenType.Number)
  237. {
  238. reader.TryGetDouble(out double d);
  239. return d;
  240. }
  241. double.TryParse(reader.GetString(), out double d2);
  242. return d2;
  243. }
  244. public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
  245. {
  246. writer.WriteStringValue(value.ToString());
  247. }
  248. }
  249. }