RequestManager.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace RESTClient
  9. {
  10. public enum RequestMethod
  11. {
  12. GET,
  13. POST,
  14. PUT,
  15. DELETE,
  16. }
  17. public class RequestManager
  18. {
  19. public struct Response
  20. {
  21. public int statusCode;
  22. public string statusCodeName;
  23. public string content;
  24. }
  25. private static RequestManager singleton = null;
  26. public static RequestManager Get()
  27. {
  28. return singleton = new RequestManager();
  29. }
  30. private HttpClient client;
  31. private RequestManager()
  32. {
  33. client = new HttpClient();
  34. }
  35. public async Task<Response> SendRequest(string target, RequestMethod method, HttpContent body)
  36. {
  37. HttpResponseMessage httpResponse = null;
  38. try
  39. {
  40. switch (method)
  41. {
  42. case RequestMethod.DELETE:
  43. httpResponse = await client.DeleteAsync(target); break;
  44. case RequestMethod.GET:
  45. httpResponse = await client.GetAsync(target); break;
  46. case RequestMethod.POST:
  47. httpResponse = await client.PostAsync(target, body); break;
  48. case RequestMethod.PUT:
  49. httpResponse = await client.PutAsync(target, body); break;
  50. }
  51. }
  52. catch (Exception e)
  53. {
  54. return new Response
  55. {
  56. statusCode = 0,
  57. statusCodeName = "ERROR",
  58. content = e.Message
  59. };
  60. }
  61. Response response = new Response();
  62. HttpStatusCode responseStatus = httpResponse.StatusCode;
  63. response.statusCode = (int)responseStatus;
  64. response.statusCodeName = responseStatus.ToString();
  65. HttpContent responseContent = httpResponse.Content;
  66. response.content = await responseContent.ReadAsStringAsync();
  67. httpResponse.Dispose();
  68. return response;
  69. }
  70. }
  71. }