DefaultTopClient.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. using FastJSON;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Xml;
  6. using Top.Api.Parser;
  7. using Top.Api.Util;
  8. namespace Top.Api
  9. {
  10. /// <summary>
  11. /// 基于REST的TOP客户端。
  12. /// </summary>
  13. public class DefaultTopClient : ITopClient
  14. {
  15. internal string serverUrl;
  16. internal string appKey;
  17. internal string appSecret;
  18. internal string format = Constants.FORMAT_XML;
  19. internal WebUtils webUtils;
  20. internal ITopLogger topLogger;
  21. internal bool disableParser = false; // 禁用响应结果解释
  22. internal bool disableTrace = false; // 禁用日志调试功能
  23. internal bool useSimplifyJson = false; // 是否采用精简化的JSON返回
  24. internal bool useGzipEncoding = true; // 是否启用响应GZIP压缩
  25. internal IDictionary<string, string> systemParameters; // 设置所有请求共享的系统级参数
  26. #region DefaultTopClient Constructors
  27. public DefaultTopClient(string serverUrl, string appKey, string appSecret)
  28. {
  29. this.appKey = appKey;
  30. this.appSecret = appSecret;
  31. this.serverUrl = serverUrl;
  32. this.webUtils = new WebUtils();
  33. this.topLogger = Top.Api.Log.Instance;
  34. }
  35. public DefaultTopClient(string serverUrl, string appKey, string appSecret, string format)
  36. : this(serverUrl, appKey, appSecret)
  37. {
  38. this.format = format;
  39. }
  40. #endregion
  41. public void SetTimeout(int timeout)
  42. {
  43. this.webUtils.Timeout = timeout;
  44. }
  45. public void SetReadWriteTimeout(int readWriteTimeout)
  46. {
  47. this.webUtils.ReadWriteTimeout = readWriteTimeout;
  48. }
  49. public void SetDisableParser(bool disableParser)
  50. {
  51. this.disableParser = disableParser;
  52. }
  53. public void SetDisableTrace(bool disableTrace)
  54. {
  55. this.disableTrace = disableTrace;
  56. }
  57. public void SetUseSimplifyJson(bool useSimplifyJson)
  58. {
  59. this.useSimplifyJson = useSimplifyJson;
  60. }
  61. public void SetUseGzipEncoding(bool useGzipEncoding)
  62. {
  63. this.useGzipEncoding = useGzipEncoding;
  64. }
  65. public void SetIgnoreSSLCheck(bool ignore)
  66. {
  67. this.webUtils.IgnoreSSLCheck = ignore;
  68. }
  69. /// <summary>
  70. /// 禁用本地代理自动检测功能,加快连接建立速度
  71. /// </summary>
  72. public void SetDisableWebProxy(bool disable)
  73. {
  74. this.webUtils.DisableWebProxy = disable;
  75. }
  76. /// <summary>
  77. /// 设置单个网站最大并发连接数,桌面端默认是2,服务器端默认是10,对于桌面端并发请求多的,可以适当调高。
  78. /// </summary>
  79. /// <param name="limit"></param>
  80. public void SetMaxConnectionLimit(int limit)
  81. {
  82. System.Net.ServicePointManager.DefaultConnectionLimit = limit;
  83. }
  84. public void SetSystemParameters(IDictionary<string, string> systemParameters)
  85. {
  86. this.systemParameters = systemParameters;
  87. }
  88. #region ITopClient Members
  89. public virtual T Execute<T>(ITopRequest<T> request) where T : TopResponse
  90. {
  91. return DoExecute<T>(request, null, DateTime.Now);
  92. }
  93. public virtual T Execute<T>(ITopRequest<T> request, string session) where T : TopResponse
  94. {
  95. return DoExecute<T>(request, session, DateTime.Now);
  96. }
  97. public virtual T Execute<T>(ITopRequest<T> request, string session, DateTime timestamp) where T : TopResponse
  98. {
  99. return DoExecute<T>(request, session, timestamp);
  100. }
  101. #endregion
  102. private T DoExecute<T>(ITopRequest<T> request, string session, DateTime timestamp) where T : TopResponse
  103. {
  104. long start = DateTime.Now.Ticks;
  105. // 提前检查业务参数
  106. try
  107. {
  108. request.Validate();
  109. }
  110. catch (TopException e)
  111. {
  112. return CreateErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
  113. }
  114. // 添加协议级请求参数
  115. TopDictionary txtParams = new TopDictionary(request.GetParameters());
  116. txtParams.Add(Constants.METHOD, request.GetApiName());
  117. txtParams.Add(Constants.VERSION, "2.0");
  118. txtParams.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
  119. txtParams.Add(Constants.APP_KEY, appKey);
  120. txtParams.Add(Constants.FORMAT, format);
  121. txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
  122. txtParams.Add(Constants.TIMESTAMP, timestamp);
  123. txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
  124. txtParams.Add(Constants.SESSION, session);
  125. txtParams.AddAll(this.systemParameters);
  126. if (this.useSimplifyJson)
  127. {
  128. txtParams.Add(Constants.SIMPLIFY, "true");
  129. }
  130. // 添加签名参数
  131. txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, appSecret, Constants.SIGN_METHOD_HMAC));
  132. // 添加头部参数
  133. if (this.useGzipEncoding)
  134. {
  135. request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
  136. }
  137. string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
  138. string reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
  139. try
  140. {
  141. string body;
  142. if (request is ITopUploadRequest<T>) // 是否需要上传文件
  143. {
  144. ITopUploadRequest<T> uRequest = (ITopUploadRequest<T>)request;
  145. IDictionary<string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
  146. body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
  147. }
  148. else
  149. {
  150. body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
  151. }
  152. // 解释响应结果
  153. T rsp;
  154. if (disableParser)
  155. {
  156. rsp = Activator.CreateInstance<T>();
  157. rsp.Body = body;
  158. }
  159. else
  160. {
  161. if (Constants.FORMAT_XML.Equals(format))
  162. {
  163. ITopParser<T> tp = new TopXmlParser<T>();
  164. rsp = tp.Parse(body);
  165. }
  166. else
  167. {
  168. ITopParser<T> tp;
  169. if (useSimplifyJson)
  170. {
  171. tp = new TopSimplifyJsonParser<T>();
  172. }
  173. else
  174. {
  175. tp = new TopJsonParser<T>();
  176. }
  177. rsp = tp.Parse(body);
  178. }
  179. }
  180. // 追踪错误的请求
  181. if (rsp.IsError)
  182. {
  183. TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
  184. TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
  185. }
  186. return rsp;
  187. }
  188. catch (Exception e)
  189. {
  190. TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
  191. TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
  192. throw e;
  193. }
  194. }
  195. internal virtual string GetServerUrl(string serverUrl, string apiName, string session)
  196. {
  197. return serverUrl;
  198. }
  199. internal virtual string GetSdkVersion()
  200. {
  201. return Constants.SDK_VERSION;
  202. }
  203. internal T CreateErrorResponse<T>(string errCode, string errMsg) where T : TopResponse
  204. {
  205. T rsp = Activator.CreateInstance<T>();
  206. rsp.ErrCode = errCode;
  207. rsp.ErrMsg = errMsg;
  208. if (Constants.FORMAT_XML.Equals(format))
  209. {
  210. XmlDocument root = new XmlDocument();
  211. XmlElement bodyE = root.CreateElement(Constants.ERROR_RESPONSE);
  212. XmlElement codeE = root.CreateElement(Constants.ERROR_CODE);
  213. codeE.InnerText = errCode;
  214. bodyE.AppendChild(codeE);
  215. XmlElement msgE = root.CreateElement(Constants.ERROR_MSG);
  216. msgE.InnerText = errMsg;
  217. bodyE.AppendChild(msgE);
  218. root.AppendChild(bodyE);
  219. rsp.Body = root.OuterXml;
  220. }
  221. else
  222. {
  223. IDictionary<string, object> errObj = new Dictionary<string, object>();
  224. errObj.Add(Constants.ERROR_CODE, errCode);
  225. errObj.Add(Constants.ERROR_MSG, errMsg);
  226. IDictionary<string, object> root = new Dictionary<string, object>();
  227. root.Add(Constants.ERROR_RESPONSE, errObj);
  228. string body = JSON.ToJSON(root);
  229. rsp.Body = body;
  230. }
  231. return rsp;
  232. }
  233. internal void TraceApiError(string appKey, string apiName, string url, Dictionary<string, string> parameters, double latency, string errorMessage)
  234. {
  235. if (!disableTrace)
  236. {
  237. this.topLogger.TraceApiError(appKey, apiName, url, parameters, latency, errorMessage);
  238. }
  239. }
  240. }
  241. }