HttpClientHelper.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections.Generic;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. namespace GxPress.Common.Http
  5. {
  6. /// <summary>
  7. /// HttpClient
  8. /// </summary>
  9. public static class HttpClientHelper
  10. {
  11. /// <summary>
  12. /// get
  13. /// </summary>
  14. /// <param name="url"></param>
  15. /// <param name="headers"></param>
  16. /// <returns></returns>
  17. public static async Task<HttpResponseMessage> GetHeadersAsync(string url,Dictionary<string,string> headers)
  18. {
  19. HttpClient httpClient = new HttpClient(); //http对象
  20. //添加header
  21. foreach (var header in headers)
  22. {
  23. httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
  24. }
  25. var response = await httpClient.GetAsync(url);
  26. return response;
  27. }
  28. /// <summary>
  29. /// 根据地址下载
  30. /// </summary>
  31. /// <param name="url"></param>
  32. /// <returns></returns>
  33. public static async Task<byte[]> GetByteArrayAsync(string url)
  34. {
  35. HttpClient httpClient = new HttpClient(); //http对象
  36. var response = await httpClient.GetByteArrayAsync(url);
  37. return response;
  38. }
  39. /// <summary>
  40. /// post
  41. /// </summary>
  42. /// <param name="url"></param>
  43. /// <param name="jsonObj">json</param>
  44. /// <param name="headers"></param>
  45. /// <returns></returns>
  46. public static async Task<HttpResponseMessage> PostAsync(string url, object jsonObj,
  47. Dictionary<string, string> headers = null)
  48. {
  49. HttpClient httpClient = new HttpClient(); //http对象
  50. if (headers != null)
  51. foreach (var header in headers)
  52. {
  53. httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
  54. }
  55. HttpResponseMessage response = await httpClient.PostAsync(url,
  56. new JsonContent(jsonObj));
  57. return response;
  58. }
  59. /// <summary>
  60. /// rest删除
  61. /// </summary>
  62. /// <param name="url"></param>
  63. /// <param name="headers"></param>
  64. /// <returns></returns>
  65. public static async Task<HttpResponseMessage> DeleteAsync(string url, Dictionary<string, string> headers = null)
  66. {
  67. HttpClient httpClient = new HttpClient(); //http对象
  68. if (headers != null)
  69. foreach (var header in headers)
  70. {
  71. httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
  72. }
  73. HttpResponseMessage response = await httpClient.DeleteAsync(url);
  74. return response;
  75. }
  76. }
  77. }