12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- using Newtonsoft.Json;
- using SinochemPosClient.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- namespace SinochemPosClient
- {
- public class PosCommunicator<TRequest, TResponse>
- where TRequest : RequestBase
- where TResponse : ResponseBase
- {
- private HttpClient client;
- private string url;
- public PosCommunicator(string apiUrl)
- {
- client = new HttpClient();
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- this.url = apiUrl;
- }
- public void SendRequest(TRequest request)
- {
- try
- {
- var requestAsJson = JsonConvert.SerializeObject(request);
- var formVariables = new List<KeyValuePair<string, string>>();
- formVariables.Add(new KeyValuePair<string, string>("param", requestAsJson));
- var formContent = new FormUrlEncodedContent(formVariables);
- HttpResponseMessage httpResponse = client.PostAsync(url, formContent).Result;
- httpResponse.EnsureSuccessStatusCode();
- Response = JsonConvert.DeserializeObject<TResponse>(httpResponse.Content.ReadAsStringAsync().Result);//.ReadAsAsync<TResponse>().Result;
- }
- catch (Exception ex)
- {
- Response = null;
- Console.WriteLine(ex);
- }
- }
- public TResponse Response
- {
- get;
- private set;
- }
- }
- }
|