RestApi.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using RestSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace WCS.API.WebApiClient
  10. {
  11. public class RestApi<T> where T : class, new()
  12. {
  13. public T Get(string url, object pars, object body, out string content)
  14. {
  15. IRestResponse<T> reval = GetApiInfo(url, pars, body, Method.GET);
  16. content = reval.Content;
  17. return reval.Data;
  18. }
  19. public T Post(string url, object pars, object body, out string content)
  20. {
  21. IRestResponse<T> reval = GetApiInfo(url, pars, body, Method.POST);
  22. content = reval.Content;
  23. return reval.Data;
  24. }
  25. public T Delete(string url, object pars, object body, out string content)
  26. {
  27. IRestResponse<T> reval = GetApiInfo(url, pars, body, Method.DELETE);
  28. content = reval.Content;
  29. return reval.Data;
  30. }
  31. public T Put(string url, object pars, object body, out string content)
  32. {
  33. IRestResponse<T> reval = GetApiInfo(url, pars, body, Method.PUT);
  34. content = reval.Content;
  35. return reval.Data;
  36. }
  37. public IRestResponse<T> GetApiInfo(string url, object pars, object body, Method type)
  38. {
  39. var request = new RestRequest(type);
  40. if (pars!=null)
  41. {
  42. request.AddObject(pars);
  43. }
  44. if (body!=null)
  45. {
  46. request.AddJsonBody(body);
  47. }
  48. var client = new RestClient(url);
  49. client.AddHandler("text/plain", () => new RestSharp.Serialization.Json.JsonDeserializer());
  50. client.AddHandler("text/html", () => new RestSharp.Serialization.Json.JsonDeserializer());
  51. IRestResponse<T> reval = client.Execute<T>(request);
  52. if (reval.ErrorException!=null)
  53. {
  54. throw new Exception($"ÇëÇó³ö´í{url} {reval.ErrorMessage} {reval.Content}");
  55. }
  56. return reval;
  57. }
  58. }
  59. }