PosCommunicator.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Newtonsoft.Json;
  2. using SinochemPosClient.Models;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace SinochemPosClient
  12. {
  13. public class PosCommunicator<TRequest, TResponse>
  14. where TRequest : RequestBase
  15. where TResponse : ResponseBase
  16. {
  17. private HttpClient client;
  18. private string url;
  19. public PosCommunicator(string apiUrl)
  20. {
  21. client = new HttpClient();
  22. client.DefaultRequestHeaders.Accept.Clear();
  23. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  24. this.url = apiUrl;
  25. }
  26. public void SendRequest(TRequest request)
  27. {
  28. try
  29. {
  30. var requestAsJson = JsonConvert.SerializeObject(request);
  31. var formVariables = new List<KeyValuePair<string, string>>();
  32. formVariables.Add(new KeyValuePair<string, string>("param", requestAsJson));
  33. var formContent = new FormUrlEncodedContent(formVariables);
  34. HttpResponseMessage httpResponse = client.PostAsync(url, formContent).Result;
  35. httpResponse.EnsureSuccessStatusCode();
  36. Response = JsonConvert.DeserializeObject<TResponse>(httpResponse.Content.ReadAsStringAsync().Result);//.ReadAsAsync<TResponse>().Result;
  37. }
  38. catch (Exception ex)
  39. {
  40. Response = null;
  41. Console.WriteLine(ex);
  42. }
  43. }
  44. public TResponse Response
  45. {
  46. get;
  47. private set;
  48. }
  49. }
  50. }