DefaultQimenCloudClient.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Xml;
  5. using QimenCloud.Api.Parser;
  6. using Top.Api;
  7. using Top.Api.Parser;
  8. using Top.Api.Util;
  9. using FastJSON;
  10. using System.Collections;
  11. using XmlWriter = Top.Api.Util.XmlWriter;
  12. namespace QimenCloud.Api
  13. {
  14. public class DefaultQimenCloudClient : IQimenCloudClient
  15. {
  16. internal string serverUrl;
  17. internal string appKey;
  18. internal string appSecret;
  19. internal string format = Constants.FORMAT_JSON;
  20. internal string signMethod = Constants.SIGN_METHOD_HMAC_SHA256;
  21. internal WebUtils webUtils;
  22. internal ITopLogger topLogger;
  23. internal bool disableParser = false; // 禁用响应结果解释
  24. internal bool disableTrace = false; // 禁用日志调试功能
  25. internal bool useGzipEncoding = true; // 是否启用响应GZIP压缩
  26. internal IDictionary<string, string> systemParameters; // 设置所有请求共享的系统级参数
  27. #region DefaultQimenCloudClient Constructors
  28. public DefaultQimenCloudClient(string serverUrl, string appKey, string appSecret)
  29. {
  30. this.appKey = appKey;
  31. this.appSecret = appSecret;
  32. this.serverUrl = serverUrl;
  33. this.webUtils = new WebUtils();
  34. this.topLogger = Log.Instance;
  35. }
  36. public DefaultQimenCloudClient(string serverUrl, string appKey, string appSecret, string format)
  37. : this(serverUrl, appKey, appSecret)
  38. {
  39. this.format = format;
  40. }
  41. #endregion
  42. public void SetTimeout(int timeout)
  43. {
  44. this.webUtils.Timeout = timeout;
  45. }
  46. public void SetReadWriteTimeout(int readWriteTimeout)
  47. {
  48. this.webUtils.ReadWriteTimeout = readWriteTimeout;
  49. }
  50. public void SetSignMethod(String signMethod)
  51. {
  52. this.signMethod = signMethod;
  53. }
  54. public void SetDisableParser(bool disableParser)
  55. {
  56. this.disableParser = disableParser;
  57. }
  58. public void SetDisableTrace(bool disableTrace)
  59. {
  60. this.disableTrace = disableTrace;
  61. }
  62. public void SetUseGzipEncoding(bool useGzipEncoding)
  63. {
  64. this.useGzipEncoding = useGzipEncoding;
  65. }
  66. public void SetIgnoreSSLCheck(bool ignore)
  67. {
  68. this.webUtils.IgnoreSSLCheck = ignore;
  69. }
  70. public void SetSystemParameters(IDictionary<string, string> systemParameters)
  71. {
  72. this.systemParameters = systemParameters;
  73. }
  74. #region ITopClient Members
  75. public virtual T Execute<T>(IQimenCloudRequest<T> request) where T : QimenCloudResponse
  76. {
  77. return DoExecute<T>(request, null, DateTime.Now);
  78. }
  79. public virtual T Execute<T>(IQimenCloudRequest<T> request, string session) where T : QimenCloudResponse
  80. {
  81. return DoExecute<T>(request, session, DateTime.Now);
  82. }
  83. public virtual T Execute<T>(IQimenCloudRequest<T> request, string session, DateTime timestamp) where T : QimenCloudResponse
  84. {
  85. return DoExecute<T>(request, session, timestamp);
  86. }
  87. #endregion
  88. private T DoExecute<T>(IQimenCloudRequest<T> request, string session, DateTime timestamp) where T : QimenCloudResponse
  89. {
  90. long start = DateTime.Now.Ticks;
  91. // 提前检查业务参数
  92. try
  93. {
  94. request.Validate();
  95. }
  96. catch (TopException e)
  97. {
  98. return CreateErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
  99. }
  100. // 兼容 老奇门1.0 的 XML BODY
  101. String apiBody = null;
  102. Object[] requestXmlBodyType = request.GetType().GetCustomAttributes(typeof(RequestXmlBodyAttribute), false);
  103. Boolean isXmlBody = (requestXmlBodyType != null && requestXmlBodyType.Length > 0);
  104. if (isXmlBody)
  105. {
  106. XmlWriter writer = new XmlWriter(Constants.QM_ROOT_TAG_REQ, typeof(IQimenCloudRequest<T>));
  107. apiBody = writer.Write(request);
  108. }
  109. // 添加协议级请求参数
  110. TopDictionary txtParams = new TopDictionary(request.GetParameters());
  111. txtParams.Add(Constants.METHOD, request.GetApiName());
  112. txtParams.Add(Constants.SIGN_METHOD, signMethod);
  113. txtParams.Add(Constants.APP_KEY, appKey);
  114. txtParams.Add(Constants.FORMAT, format);
  115. txtParams.Add(Constants.VERSION, "2.0");
  116. txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
  117. txtParams.Add(Constants.TIMESTAMP, timestamp);
  118. txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
  119. txtParams.Add(Constants.SESSION, session);
  120. txtParams.AddAll(this.systemParameters);
  121. // 添加签名参数
  122. if (isXmlBody)
  123. {
  124. txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, apiBody, appSecret, signMethod));
  125. }
  126. else
  127. {
  128. txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, appSecret, signMethod));
  129. }
  130. // 添加头部参数
  131. if (this.useGzipEncoding)
  132. {
  133. request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
  134. }
  135. string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
  136. string reqUrl;
  137. if (isXmlBody)
  138. {
  139. reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
  140. }
  141. else
  142. {
  143. reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
  144. }
  145. try
  146. {
  147. string body;
  148. if (isXmlBody)
  149. {
  150. body = webUtils.DoPost(reqUrl, Encoding.UTF8.GetBytes(apiBody), Constants.QM_CONTENT_TYPE, request.GetHeaderParameters());
  151. }
  152. else
  153. {
  154. body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
  155. }
  156. // 解释响应结果
  157. T rsp;
  158. if (disableParser)
  159. {
  160. rsp = Activator.CreateInstance<T>();
  161. rsp.Body = body;
  162. rsp.RequestUrl = reqUrl;
  163. }
  164. else
  165. {
  166. if (Constants.FORMAT_XML.Equals(format))
  167. {
  168. ITopParser<T> tp = new QimenCloudXmlParser<T>();
  169. rsp = tp.Parse(body);
  170. }
  171. else
  172. {
  173. ITopParser<T> tp = new QimenCloudSimplifyJsonParser<T>();
  174. rsp = tp.Parse(body);
  175. }
  176. rsp.RequestUrl = reqUrl;
  177. }
  178. // 追踪错误的请求
  179. if (rsp.IsError)
  180. {
  181. TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
  182. TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
  183. }
  184. return rsp;
  185. }
  186. catch (Exception e)
  187. {
  188. TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
  189. TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
  190. throw e;
  191. }
  192. }
  193. internal virtual string GetServerUrl(string serverUrl, string apiName, string session)
  194. {
  195. return serverUrl;
  196. }
  197. internal virtual string GetSdkVersion()
  198. {
  199. return Constants.SDK_VERSION;
  200. }
  201. internal T CreateErrorResponse<T>(string errCode, string errMsg) where T : QimenCloudResponse
  202. {
  203. T rsp = Activator.CreateInstance<T>();
  204. rsp.Code = errCode;
  205. rsp.Message = errMsg;
  206. if (Constants.FORMAT_XML.Equals(format))
  207. {
  208. XmlDocument root = new XmlDocument();
  209. XmlElement bodyE = root.CreateElement(Constants.ERROR_RESPONSE);
  210. XmlElement codeE = root.CreateElement(Constants.ERROR_CODE);
  211. codeE.InnerText = errCode;
  212. bodyE.AppendChild(codeE);
  213. XmlElement msgE = root.CreateElement(Constants.ERROR_MSG);
  214. msgE.InnerText = errMsg;
  215. bodyE.AppendChild(msgE);
  216. root.AppendChild(bodyE);
  217. rsp.Body = root.OuterXml;
  218. }
  219. else
  220. {
  221. IDictionary<string, object> errObj = new Dictionary<string, object>();
  222. errObj.Add(Constants.ERROR_CODE, errCode);
  223. errObj.Add(Constants.ERROR_MSG, errMsg);
  224. IDictionary<string, object> root = new Dictionary<string, object>();
  225. root.Add(Constants.ERROR_RESPONSE, errObj);
  226. string body = JSON.ToJSON(root);
  227. rsp.Body = body;
  228. }
  229. return rsp;
  230. }
  231. internal void TraceApiError(string appKey, string apiName, string url, Dictionary<string, string> parameters, double latency, string errorMessage)
  232. {
  233. if (!disableTrace)
  234. {
  235. this.topLogger.TraceApiError(appKey, apiName, url, parameters, latency, errorMessage);
  236. }
  237. }
  238. }
  239. }