.net6.0 webapi demo

HttpHelper.cs 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Extensions.Logging;
  6. namespace Net6Demo_Api.Util
  7. {
  8. public class HttpHelper
  9. {
  10. private readonly HttpClient _client;
  11. private readonly ILogger<HttpHelper> _logger;
  12. public HttpHelper(HttpClient client, ILogger<HttpHelper> logger)
  13. {
  14. _client = client;
  15. _logger = logger;
  16. }
  17. /// <summary>
  18. /// get请求
  19. /// </summary>
  20. /// <param name="url">请求地址</param>
  21. /// <returns></returns>
  22. public async Task<string> GetAsync(string url)
  23. {
  24. var response = await _client.GetAsync(url);
  25. if (response.IsSuccessStatusCode)
  26. {
  27. var result = await response.Content.ReadAsStringAsync();
  28. _logger.LogInformation("get请求url:" + url + ";返回结果:" + result);
  29. return result;
  30. }
  31. else
  32. {
  33. _logger.LogError("get请求url:"+ url +";返回结果:"+ response.ToJson());
  34. return "";
  35. }
  36. }
  37. /// <summary>
  38. /// post请求
  39. /// </summary>
  40. /// <param name="url">请求地址</param>
  41. /// <param name="param">参数</param>
  42. /// <param name="contenttype">请求类型(默认application/json)</param>
  43. /// <returns></returns>
  44. public async Task<string> PostAsync(string url, string? param = null, string contenttype = "application/json")
  45. {
  46. var requestContent = new StringContent(param ?? "", Encoding.UTF8, contenttype);
  47. var response = await _client.PostAsync(url, requestContent);
  48. if (response.IsSuccessStatusCode)
  49. {
  50. var result = await response.Content.ReadAsStringAsync();
  51. return result;
  52. }
  53. else
  54. {
  55. _logger.LogError("post请求url:" + url + ";参数:" + param + "返回结果:" + response.ToJson());
  56. return "";
  57. }
  58. }
  59. /// <summary>
  60. /// put请求
  61. /// </summary>
  62. /// <param name="url">请求地址</param>
  63. /// <param name="param">参数</param>
  64. /// <param name="contenttype">请求类型(默认application/json)</param>
  65. /// <returns></returns>
  66. public async Task<string> PutAsync(string url, string? param = null, string contenttype = "application/json")
  67. {
  68. var requestContent = new StringContent(param ?? "", Encoding.UTF8, contenttype);
  69. var response = await _client.PutAsync(url, requestContent);
  70. if (response.IsSuccessStatusCode)
  71. {
  72. var result = await response.Content.ReadAsStringAsync();
  73. return result;
  74. }
  75. else
  76. {
  77. _logger.LogError("put请求url:" + url + ";参数:" + param + "返回结果:" + response.ToJson());
  78. return "";
  79. }
  80. }
  81. }
  82. }