CloudCommunicator.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using SinochemCloudClient.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Net.Http.Headers;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace SinochemCloudClient
  10. {
  11. public class CloudCommunicator<TRequest, TResponse>
  12. where TRequest : RequestBase
  13. where TResponse : ResponseBase
  14. {
  15. private HttpClient client;
  16. private string url;
  17. public CloudCommunicator(string apiUrl)
  18. {
  19. client = new HttpClient();
  20. client.DefaultRequestHeaders.Accept.Clear();
  21. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  22. this.url = apiUrl;
  23. }
  24. public void SendRequest(TRequest request)
  25. {
  26. try
  27. {
  28. HttpResponseMessage httpResponse = client.PostAsJsonAsync<TRequest>(url, request).Result;
  29. httpResponse.EnsureSuccessStatusCode();
  30. Response = httpResponse.Content.ReadAsAsync<TResponse>().Result;
  31. }
  32. catch (Exception ex)
  33. {
  34. Response = null;
  35. Console.WriteLine(ex);
  36. }
  37. }
  38. public TResponse Response
  39. {
  40. get;
  41. private set;
  42. }
  43. }
  44. }