RestApi.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using ProjectManagementSystem.Language;
  2. using RestSharp;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace ProjectManagementSystem.Common.Service
  12. {
  13. public class RestApi
  14. {
  15. private RestClient client = new RestClient();
  16. public RestApi()
  17. {
  18. //client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin", "123456");
  19. //client.CookieContainer = new System.Net.CookieContainer();
  20. //client.ClearHandlers();
  21. //client.AddHandler("text/plain", () => new RestSharp.Serialization.Json.JsonDeserializer());
  22. }
  23. public T Get<T>(string url, object pars, object body, out string content)
  24. {
  25. var reval = GetApiInfo<T>(url, pars, null, body, Method.GET);
  26. content = reval.Content;
  27. return reval.Data;
  28. }
  29. public T Post<T>(string url, object pars, object body, out string content)
  30. {
  31. var reval = GetApiInfo<T>(url, pars, null, body, Method.POST);
  32. content = reval.Content;
  33. return reval.Data;
  34. }
  35. public T Delete<T>(string url, object pars, object body, out string content)
  36. {
  37. var reval = GetApiInfo<T>(url, pars, null, body, Method.DELETE);
  38. content = reval.Content;
  39. return reval.Data;
  40. }
  41. public T Put<T>(string url, object pars, object body, out string content)
  42. {
  43. var reval = GetApiInfo<T>(url, pars, null, body, Method.PUT);
  44. content = reval.Content;
  45. return reval.Data;
  46. }
  47. public IRestResponse<T> GetApiInfo<T>(string url, object pars, Dictionary<string, string> header, object body, Method type)
  48. {
  49. var request = new RestRequest(url, type);
  50. if (pars != null)
  51. {
  52. request.AddObject(pars);
  53. }
  54. if (header != null)
  55. {
  56. request.AddHeaders(header);
  57. }
  58. if (body != null)
  59. {
  60. request.AddJsonBody(body);
  61. }
  62. IRestResponse<T> reval = client.Execute<T>(request);
  63. if (reval.ErrorException != null)
  64. {
  65. throw new Exception($"{Langs.RequestError} {url} {reval.ErrorMessage} {reval.Content}");
  66. }
  67. return reval;
  68. }
  69. }
  70. }