HttpClientHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Windows.Web.Http;
  7. namespace KdanCommon.Helpers
  8. {
  9. public static class HttpClientHelper
  10. {
  11. public static KeyValuePair<string, string> CreateQuery(string param, string value)
  12. {
  13. return new KeyValuePair<string, string>(param, value);
  14. }
  15. public static async Task<HttpResponseMessage> GetRequest(this HttpClient httpClient, Uri requestUri, List<KeyValuePair<string, string>> querys)
  16. {
  17. requestUri = new Uri(requestUri.AbsoluteUri + querys.HttpQueryString());
  18. var result = new HttpResponseMessage();
  19. try
  20. {
  21. result = await httpClient.GetAsync(requestUri);
  22. }
  23. catch (Exception ex)
  24. {
  25. var ii = ex.Data;
  26. result.StatusCode = HttpStatusCode.RequestTimeout;
  27. }
  28. return result;
  29. }
  30. public static async Task<HttpResponseMessage> PostRequest(this HttpClient httpClient, Uri requestUri, List<KeyValuePair<string, string>> querys)
  31. {
  32. var content = new HttpFormUrlEncodedContent(querys);
  33. var result = new HttpResponseMessage();
  34. try
  35. {
  36. result = await httpClient.PostAsync(requestUri, content);
  37. }
  38. catch (Exception ex)
  39. {
  40. var ii = ex.Data;
  41. result.StatusCode = HttpStatusCode.RequestTimeout;
  42. }
  43. return result;
  44. }
  45. public static async Task<HttpResponseMessage> PutRequest(this HttpClient httpClient, Uri requestUri, List<KeyValuePair<string, string>> querys)
  46. {
  47. var content = new HttpFormUrlEncodedContent(querys);
  48. var result = await httpClient.PutAsync(requestUri, content);
  49. return result;
  50. }
  51. public static async Task<HttpResponseMessage> DeleteRequest(this HttpClient httpClient, Uri requestUri, List<KeyValuePair<string, string>> querys)
  52. {
  53. // requestUri = new Uri(requestUri.AbsoluteUri + HttpQueryString(querys));
  54. HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, requestUri);
  55. request.Content = new HttpFormUrlEncodedContent(querys);
  56. var result = await httpClient.SendRequestAsync(request);
  57. return result;
  58. }
  59. public static string HttpQueryString(this List<KeyValuePair<string, string>> querys)
  60. {
  61. var queryString = "?";
  62. foreach (var q in querys)
  63. {
  64. queryString += q.Key + "=" + q.Value + "&";
  65. }
  66. queryString = queryString.Remove(queryString.Length - 1);
  67. return queryString;
  68. }
  69. }
  70. }