WebClientHelper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Microsoft.Extensions.Configuration;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.IO;
  8. using System.Net;
  9. using System.Collections.Specialized;
  10. namespace WebAPIBase.Utils
  11. {
  12. public class WebClientHelper
  13. {
  14. //private string url;
  15. public WebClientHelper()
  16. {
  17. //IConfigurationBuilder builder = new ConfigurationBuilder()
  18. // .SetBasePath(Directory.GetCurrentDirectory())
  19. // .AddJsonFile("appsettings.json");
  20. //IConfigurationRoot Configuration = builder.Build();
  21. //url = Configuration["Logging:AppSettings:webserviceUrl"];
  22. }
  23. /// <summary>
  24. /// http post
  25. /// </summary>
  26. /// <param name="url"></param>
  27. /// <param name="postValues"></param>
  28. /// <returns></returns>
  29. public static string ClientPost(string url, NameValueCollection postValues)
  30. {
  31. try
  32. {
  33. Console.WriteLine($"url:{url}");
  34. WebClient webClient = new WebClient();
  35. // 向服务器发送POST数据
  36. byte[] responseArray = webClient.UploadValues(url, "POST", postValues);
  37. string response = Encoding.UTF8.GetString(responseArray);
  38. return response;
  39. }
  40. catch (Exception ex)
  41. {
  42. throw;
  43. }
  44. }
  45. /// <summary>
  46. /// http get
  47. /// </summary>
  48. /// <param name="url"></param>
  49. /// <param name="getValues"></param>
  50. /// <returns></returns>
  51. public static string ClientGet(string url, NameValueCollection getValues)
  52. {
  53. try
  54. {
  55. WebClient webClient = new WebClient();
  56. // 向服务器发送POST数据
  57. byte[] responseArray = webClient.UploadValues(url, "GET", getValues);
  58. string response = Encoding.UTF8.GetString(responseArray);
  59. return response;
  60. }
  61. catch (Exception ex)
  62. {
  63. throw;
  64. }
  65. }
  66. }
  67. }