HttpHelper.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Business.Core.Utilities
  7. {
  8. public class HttpHelper
  9. {/// <summary>
  10. /// 发起POST同步请求
  11. ///
  12. /// </summary>
  13. /// <param name="url"></param>
  14. /// <param name="postData"></param>
  15. /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
  16. /// <param name="headers">填充消息头</param>
  17. /// <returns></returns>
  18. public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
  19. {
  20. public static string HttpGet(string url, Dictionary<string, string>? headers = null)
  21. {
  22. HttpClient client = new HttpClient();
  23. if (headers != null)
  24. {
  25. foreach (var header in headers)
  26. {
  27. client.DefaultRequestHeaders.Add(header.Key, header.Value);
  28. }
  29. using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
  30. {
  31. if (contentType != null)
  32. httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
  33. HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
  34. return response.Content.ReadAsStringAsync().Result;
  35. }
  36. try
  37. {
  38. byte[] resultBytes = client.GetByteArrayAsync(url).Result;
  39. return Encoding.UTF8.GetString(resultBytes);
  40. }
  41. catch
  42. {
  43. return string.Empty;
  44. }
  45. }
  46. public static string HttpPost(string url, string postData, Dictionary<string, string>? headers = null, string contentType = "", int timeout = 0, Encoding? encoding = null)
  47. {
  48. HttpClient client = new HttpClient();
  49. if (headers != null)
  50. {
  51. foreach (var header in headers)
  52. {
  53. client.DefaultRequestHeaders.Add(header.Key, header.Value);
  54. }
  55. HttpResponseMessage response = client.GetAsync(url).Result;
  56. return response.Content.ReadAsStringAsync().Result;
  57. }
  58. }
  59. HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8);
  60. if (!string.IsNullOrWhiteSpace(contentType))
  61. {
  62. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
  63. }
  64. try
  65. {
  66. using HttpResponseMessage responseMessage = client.PostAsync(url, content).Result;
  67. byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
  68. return Encoding.UTF8.GetString(resultBytes);
  69. }
  70. catch
  71. {
  72. return string.Empty;
  73. }
  74. }
  75. }
  76. }