DefaultCoreClient.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using Amazon.Runtime.Internal;
  2. using Newtonsoft.Json.Serialization;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace Business.Core.HttpHelper
  11. {
  12. public class DefaultCoreClient : ICoreClient
  13. {
  14. public string Endpoint { get; }
  15. public string ContentType { get; set; }
  16. public string UserAgent { get; set; }
  17. public string Accept { get; set; }
  18. public string Host { get; set; }
  19. public string Referer { get; set; }
  20. public bool KeepAlive { get; set; }
  21. public int Timeout { get; set; }
  22. public CookieContainer CookieContainer { get; set; }
  23. public DefaultCoreClient(string endpoint)
  24. {
  25. Endpoint = endpoint;
  26. KeepAlive = true;
  27. Timeout = 10000;
  28. ContentType = "application/x-www-form-urlencoded";
  29. UserAgent = "Mozilla/5.0 (Linux; Android 10; WLZ-AL10 Build/HUAWEIWLZ-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045513 Mobile Safari/537.36 MMWEBID/4985 MicroMessenger/7.0.22.1820(0x2700163B) Process/tools WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64";
  30. Accept = "*/*";
  31. Host = "wx.sxhealth.net";
  32. Referer = "wx.sxhealth.net";
  33. CookieContainer _container = new CookieContainer();
  34. _container.Add(new Cookie("JSESSIONID", "AA644E43F2FDB7159DEC7BED2E7A2EAF", "/sxsrmyynew", "wx.sxhealth.net"));
  35. CookieContainer = _container;
  36. }
  37. protected virtual byte[] BuildBody(IDictionary<string, object> paras)
  38. {
  39. JsonSerializerSettings settings = new JsonSerializerSettings
  40. {
  41. ContractResolver = new CamelCasePropertyNamesContractResolver()
  42. };
  43. string s = JsonConvert.SerializeObject(paras, settings);
  44. return Encoding.UTF8.GetBytes(s);
  45. }
  46. protected virtual T ReadBody<T>(HttpWebResponse rsp)
  47. {
  48. T t;
  49. using (Stream responseStream = rsp.GetResponseStream())
  50. {
  51. using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
  52. {
  53. string text = streamReader.ReadToEnd();
  54. if (string.IsNullOrEmpty(text))
  55. {
  56. t = default(T);
  57. }
  58. else
  59. {
  60. Type typeFromHandle = typeof(T);
  61. string name = typeFromHandle.Name;
  62. if (name != null)
  63. {
  64. if (name == "String")
  65. {
  66. return (T)((object)Convert.ChangeType(text, typeFromHandle));
  67. }
  68. if (name == "Int32")
  69. {
  70. return (T)((object)Convert.ChangeType(int.Parse(text), typeFromHandle));
  71. }
  72. if (name == "Double")
  73. {
  74. return (T)((object)Convert.ChangeType(double.Parse(text), typeFromHandle));
  75. }
  76. if (name == "DateTime")
  77. {
  78. return (T)((object)Convert.ChangeType(DateTime.Parse(text), typeFromHandle));
  79. }
  80. }
  81. t = JsonConvert.DeserializeObject<T>(text);
  82. }
  83. }
  84. }
  85. return t;
  86. }
  87. protected virtual string ReadError(HttpWebResponse rsp)
  88. {
  89. string result;
  90. using (Stream responseStream = rsp.GetResponseStream())
  91. {
  92. using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
  93. {
  94. result = streamReader.ReadToEnd();
  95. }
  96. }
  97. return result;
  98. }
  99. HttpWebRequest BuildRequest(IRequest req)
  100. {
  101. Type attribute = typeof(HttpPropertyAttribute);
  102. Dictionary<HttpMember, Dictionary<string, object>> dictionary = req.GetType().GetProperties()
  103. .Where(p => p.IsDefined(attribute, false))
  104. .Select(p => new HttpParameter(
  105. ((HttpPropertyAttribute)p.GetCustomAttributes(attribute, false).First()).Member,
  106. p.Name,
  107. p.GetValue(req)
  108. ))
  109. .GroupBy(p => p.Member)
  110. .ToDictionary(g => g.Key, g => g.ToDictionary(p => p.Name, p => p.Value));
  111. string path = req.GetPath();
  112. string text = string.IsNullOrEmpty(path) ? Endpoint : (Endpoint + "/" + path);
  113. HttpWebRequest httpWebRequest = WebRequest.Create(text) as HttpWebRequest;
  114. httpWebRequest.Method = req.GetMethod().ToString();
  115. httpWebRequest.KeepAlive = KeepAlive;
  116. httpWebRequest.Timeout = Timeout;
  117. httpWebRequest.ContentType = ContentType;
  118. httpWebRequest.UserAgent = UserAgent;
  119. httpWebRequest.Accept = Accept;
  120. httpWebRequest.Host = Host;
  121. httpWebRequest.Referer = Referer;
  122. httpWebRequest.CookieContainer = CookieContainer;
  123. if (dictionary.TryGetValue(HttpMember.Header, out Dictionary<string, object> dictionary2))
  124. {
  125. foreach (KeyValuePair<string, object> keyValuePair in dictionary2)
  126. {
  127. httpWebRequest.Headers.Add(keyValuePair.Key, keyValuePair.Value.ToString());
  128. }
  129. }
  130. if (dictionary.TryGetValue(HttpMember.Body, out Dictionary<string, object> paras))
  131. {
  132. byte[] array = BuildBody(paras);
  133. httpWebRequest.ContentLength = array.Length;
  134. using (Stream requestStream = httpWebRequest.GetRequestStream())
  135. {
  136. requestStream.Write(array, 0, array.Length);
  137. return httpWebRequest;
  138. }
  139. }
  140. if (dictionary.TryGetValue(HttpMember.From, out Dictionary<string, object> paras2))
  141. {
  142. string s = string.Join("&", paras2.Select(r => $"{r.Key}={r.Value}").ToArray());
  143. byte[] array = Encoding.UTF8.GetBytes(s);
  144. httpWebRequest.ContentLength = array.Length;
  145. using (Stream requestStream = httpWebRequest.GetRequestStream())
  146. {
  147. requestStream.Write(array, 0, array.Length);
  148. return httpWebRequest;
  149. }
  150. }
  151. return httpWebRequest;
  152. }
  153. public virtual Response Execute(IRequest req)
  154. {
  155. Response result;
  156. try
  157. {
  158. using (HttpWebResponse httpWebResponse = BuildRequest(req).GetResponse() as HttpWebResponse)
  159. {
  160. result = new Response(httpWebResponse.StatusCode, null);
  161. }
  162. }
  163. catch (Exception ex)
  164. {
  165. if (ex is WebException && (ex as WebException).Response != null)
  166. {
  167. using (HttpWebResponse httpWebResponse2 = (ex as WebException).Response as HttpWebResponse)
  168. {
  169. return new Response(httpWebResponse2.StatusCode, ReadError(httpWebResponse2));
  170. }
  171. }
  172. result = new Response(HttpStatusCode.InternalServerError, ex.Message);
  173. }
  174. return result;
  175. }
  176. public virtual Response<T> Execute<T>(IRequest<T> req)
  177. {
  178. Response<T> result;
  179. try
  180. {
  181. using (HttpWebResponse httpWebResponse = BuildRequest(req).GetResponse() as HttpWebResponse)
  182. {
  183. result = new Response<T>(httpWebResponse.StatusCode, ReadBody<T>(httpWebResponse), null);
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. if (ex is WebException && (ex as WebException).Response != null)
  189. {
  190. using (HttpWebResponse httpWebResponse2 = (ex as WebException).Response as HttpWebResponse)
  191. {
  192. return new Response<T>(httpWebResponse2.StatusCode, default(T), ReadError(httpWebResponse2));
  193. }
  194. }
  195. result = new Response<T>(HttpStatusCode.InternalServerError, default(T), ex.Message);
  196. }
  197. return result;
  198. }
  199. public IAsyncResult BeginExecute(IRequest req, AsyncCallback callback)
  200. {
  201. return BuildRequest(req).BeginGetResponse(callback, req);
  202. }
  203. }
  204. }