Http.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. namespace DaJiaoYan.Utils
  12. {
  13. public static class Http
  14. {
  15. public struct Response
  16. {
  17. public HttpStatusCode code;
  18. public HttpContent message;
  19. public string url;
  20. }
  21. public struct Request
  22. {
  23. /// <summary>
  24. /// 请求的网址
  25. /// </summary>
  26. public string uri;
  27. /// <summary>
  28. /// 头信息
  29. /// </summary>
  30. public Dictionary<string, object> headers;
  31. /// <summary>
  32. /// 请求的数据
  33. /// </summary>
  34. public Dictionary<string, object> data;
  35. /// <summary>
  36. /// 上传的文件
  37. /// </summary>
  38. public Dictionary<string, string> files;
  39. /// <summary>
  40. /// 上传的文件二进制流
  41. /// </summary>
  42. public Dictionary<string, byte[]> fileStream;
  43. /// <summary>
  44. /// 请求类型
  45. /// </summary>
  46. public RequestContentType contentType;
  47. /// <summary>
  48. /// 请求方式
  49. /// </summary>
  50. public Method method;
  51. public void Init()
  52. {
  53. uri = "";
  54. headers = new Dictionary<string, object>();
  55. data = new Dictionary<string, object>();
  56. files = new Dictionary<string, string>();
  57. fileStream = new Dictionary<string, byte[]>();
  58. contentType = RequestContentType.Default;
  59. method = Method.Get;
  60. }
  61. public Request(string uri, Method method)
  62. {
  63. this.uri = uri;
  64. this.method = method;
  65. this.headers = new Dictionary<string, object>();
  66. this.data = null;
  67. files = null;
  68. fileStream = null;
  69. contentType = RequestContentType.Default;
  70. }
  71. public Request(string uri, Method method, Dictionary<string, object> data)
  72. {
  73. this.uri = uri;
  74. this.method = method;
  75. this.headers = new Dictionary<string, object>();
  76. this.data = data;
  77. files = null;
  78. fileStream = null;
  79. contentType = RequestContentType.Default;
  80. }
  81. public Request(string uri, Method method, Dictionary<string, object> headers, Dictionary<string, object> data)
  82. {
  83. this.uri = uri;
  84. this.method = method;
  85. this.headers = headers;
  86. this.data = data;
  87. files = null;
  88. fileStream = null;
  89. contentType = RequestContentType.Default;
  90. }
  91. public Request(string uri, Method method, RequestContentType contentType, Dictionary<string, object> headers, Dictionary<string, object> data)
  92. {
  93. this.uri = uri;
  94. this.method = method;
  95. this.headers = headers;
  96. this.data = data;
  97. files = null;
  98. fileStream = null;
  99. this.contentType = contentType;
  100. }
  101. public Request(string uri, Method method, Dictionary<string, object> headers, Dictionary<string, object> data, Dictionary<string, string> files)
  102. {
  103. this.uri = uri;
  104. this.method = method;
  105. this.headers = headers;
  106. this.data = data;
  107. this.files = files;
  108. fileStream = null;
  109. contentType = RequestContentType.Default;
  110. }
  111. public Request(string uri, Method method, Dictionary<string, object> headers, Dictionary<string, object> data, Dictionary<string, string> files, Dictionary<string, byte[]> fileStream)
  112. {
  113. this.uri = uri;
  114. this.method = method;
  115. this.headers = headers;
  116. this.data = data;
  117. this.files = files;
  118. this.fileStream = fileStream;
  119. contentType = RequestContentType.Default;
  120. }
  121. }
  122. /// <summary>
  123. /// 请求内容类型
  124. /// </summary>
  125. public enum RequestContentType
  126. {
  127. Default, Json
  128. }
  129. /// <summary>
  130. /// 请求方法
  131. /// </summary>
  132. public enum Method
  133. {
  134. Get, Post, Put, Delete, Patch
  135. }
  136. /// <summary>
  137. /// 初始化请求头
  138. /// </summary>
  139. /// <param name="httpClient"></param>
  140. /// <param name="headers"></param>
  141. private static void InitClientHeaders(ref HttpClient httpClient, Dictionary<string, object> headers)
  142. {
  143. if (headers != null)
  144. {
  145. foreach (var header in headers)
  146. {
  147. if (!string.IsNullOrEmpty(header.Key) && !string.IsNullOrEmpty(header.Value.ToString()))
  148. {
  149. httpClient.DefaultRequestHeaders.Add(header.Key, header.Value.ToString());
  150. }
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// 获取
  156. /// </summary>
  157. /// <param name="request"></param>
  158. /// <returns></returns>
  159. public static async Task<HttpResponseMessage> Fetch(Request request)
  160. {
  161. HttpResponseMessage response;
  162. try
  163. {
  164. switch (request.method)
  165. {
  166. case Method.Post:
  167. response = await Post(request);
  168. break;
  169. case Method.Put:
  170. response = await Put(request);
  171. break;
  172. case Method.Patch:
  173. response = await Patch(request);
  174. break;
  175. case Method.Delete:
  176. response = await Delete(request);
  177. break;
  178. default:
  179. response = await Get(request);
  180. break;
  181. }
  182. }
  183. catch (Exception ex)
  184. {
  185. Log.Error(ex);
  186. response = new HttpResponseMessage();
  187. }
  188. return response;
  189. }
  190. public static async Task<HttpResponseMessage> Get(Request request)
  191. {
  192. HttpResponseMessage response = null;
  193. if (!string.IsNullOrEmpty(request.uri))
  194. {
  195. HttpClient client = new HttpClient();
  196. string url = request.uri;
  197. InitClientHeaders(ref client, request.headers);
  198. if (request.data != null)
  199. {
  200. url = string.Concat(url, "?");
  201. foreach (var item in request.data)
  202. {
  203. url = string.Concat(url, $"{item.Key}={HttpUtility.UrlEncode(item.Value.ToString())}&");
  204. }
  205. url = url.Substring(0, url.Length - 1);
  206. }
  207. try
  208. {
  209. response = await client.GetAsync(url);
  210. }
  211. catch (Exception ex)
  212. {
  213. Log.Error(ex);
  214. }
  215. finally
  216. {
  217. client?.Dispose();
  218. }
  219. }
  220. return response;
  221. }
  222. private static HttpContent InitNonGetContent(Request request)
  223. {
  224. HttpContent content;
  225. if (request.contentType == RequestContentType.Json)
  226. {
  227. // 发送json 数据
  228. HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(request.data), Encoding.UTF8);
  229. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  230. content = httpContent;
  231. }
  232. else
  233. {
  234. // 普通的键值对提交
  235. MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent();
  236. if (request.files != null)
  237. {
  238. foreach (var file in request.files)
  239. {
  240. multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(file.Value)), file.Key, Path.GetFileName(file.Value));
  241. }
  242. }
  243. if (request.fileStream != null)
  244. {
  245. foreach (var file in request.fileStream)
  246. {
  247. multipartFormDataContent.Add(new ByteArrayContent(file.Value), file.Key, file.Key);
  248. }
  249. }
  250. if (request.data != null)
  251. {
  252. foreach (var d in request.data)
  253. {
  254. multipartFormDataContent.Add(new StringContent(d.Value.ToString(), Encoding.UTF8), d.Key);
  255. }
  256. }
  257. content = multipartFormDataContent;
  258. }
  259. return content;
  260. }
  261. public static async Task<HttpResponseMessage> Post(Request request)
  262. {
  263. HttpResponseMessage response = null;
  264. if (!string.IsNullOrEmpty(request.uri))
  265. {
  266. HttpClient client = new HttpClient();
  267. HttpContent content = InitNonGetContent(request);
  268. try
  269. {
  270. InitClientHeaders(ref client, request.headers);
  271. response = await client.PostAsync(request.uri, content);
  272. }
  273. catch (Exception ex)
  274. {
  275. Log.Error(ex);
  276. }
  277. finally
  278. {
  279. client?.Dispose();
  280. }
  281. }
  282. return response;
  283. }
  284. public static async Task<HttpResponseMessage> Patch(Request request)
  285. {
  286. HttpResponseMessage response = null;
  287. if (!string.IsNullOrEmpty(request.uri))
  288. {
  289. HttpClient client = new HttpClient();
  290. HttpContent content = InitNonGetContent(request);
  291. HttpRequestMessage httpRequestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), request.uri);
  292. try
  293. {
  294. InitClientHeaders(ref client, request.headers);
  295. httpRequestMessage.Content = content;
  296. response = await client.SendAsync(httpRequestMessage);
  297. }
  298. catch (Exception ex)
  299. {
  300. Log.Error(ex);
  301. }
  302. finally
  303. {
  304. client?.Dispose();
  305. }
  306. httpRequestMessage.Dispose();
  307. }
  308. return response;
  309. }
  310. public static async Task<HttpResponseMessage> Put(Request request)
  311. {
  312. HttpResponseMessage response = null;
  313. if (!string.IsNullOrEmpty(request.uri))
  314. {
  315. HttpClient client = new HttpClient();
  316. HttpContent content = InitNonGetContent(request);
  317. try
  318. {
  319. InitClientHeaders(ref client, request.headers);
  320. response = await client.PutAsync(request.uri, content);
  321. //client.Dispose();
  322. }
  323. catch (Exception ex)
  324. {
  325. Log.Error(ex);
  326. }
  327. finally
  328. {
  329. client?.Dispose();
  330. }
  331. }
  332. return response;
  333. }
  334. public static async Task<HttpResponseMessage> Delete(Request request)
  335. {
  336. HttpResponseMessage response = null;
  337. if (!string.IsNullOrEmpty(request.uri))
  338. {
  339. HttpClient client = new HttpClient();
  340. string url = request.uri;
  341. try
  342. {
  343. InitClientHeaders(ref client, request.headers);
  344. if (request.data != null)
  345. {
  346. url = string.Concat(url, "?");
  347. foreach (var item in request.data)
  348. {
  349. url = string.Concat(url, $"{item.Key}={HttpUtility.UrlEncode(item.Value.ToString())}&");
  350. }
  351. }
  352. response = await client.DeleteAsync(request.uri);
  353. }
  354. catch (Exception ex)
  355. {
  356. Log.Error(ex);
  357. }
  358. finally
  359. {
  360. client?.Dispose();
  361. }
  362. }
  363. return response;
  364. }
  365. }
  366. }