Example #1
0
        public T Execute <T>(AliSdk.Top.Api.Request.ITopRequest request, AliSdk.Top.Api.parser.ITopParser <T> parser, bool signature, string access_token)
        {
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add("timestamp", DateTime.Now);

            //是否需要用户授权令牌
            if (!string.IsNullOrEmpty(access_token))
            {
                txtParams.Add("access_token", access_token);
            }

            //添加签名参数
            string urlPath = string.Format("{0}/{1}/{2}/{3}/{4}", FORMAT, VERSION,
                                           NAMESPACE, request.GetApiName(), this.appKey);

            if (signature)
            {
                txtParams.Add("_aop_signature", TopUtils.SignTopRequest(urlPath, txtParams, appSecret));
            }

            //url
            string serverUrl = string.Format("{0}/{1}", this.url, urlPath);

            string response;

            response = WebUtils.DoPost(serverUrl, txtParams);

            return(parser.Parse(response));
        }
Example #2
0
        public void Validate(NameValueCollection parameters)
        {
            ////appid验证
            string appid = parameters.ValidateRequired(TopClient.API_KEY);

            if (appid != APPID)
            {
                throw new TopException(102, TopClient.API_KEY + " error");
            }

            //允许客户端请求时间误差为6分钟。
            ulong    timestamp    = ulong.Parse(parameters.ValidateRequired(TopClient.TIMESTAMP));
            DateTime dt           = TopUtils.UnixTimeStampToDateTime(timestamp);
            double   totalMinutes = (DateTime.Now - dt).TotalMinutes;

            if (Math.Abs(totalMinutes) > 6)
            {
                throw new TopException(102, TopClient.TIMESTAMP + " error");
            }

            //签名验证
            string psign = parameters.ValidateRequired(TopClient.SIGN);
            var    dic   = parameters.ToDictionary();

            dic.Remove(TopClient.SIGN);
            string sign = TopUtils.SignTopRequest(dic, APPSECRET);

            if (!string.Equals(sign, psign, StringComparison.OrdinalIgnoreCase))
            {
                throw new TopException(102, TopClient.SIGN + " error");
            }
        }
Example #3
0
        public IStreamImplementation GetMsgStreamImpl(TopCometStreamRequest cometReq)
        {
            if (cometReq != null)
            {
                cometReq.GetConnectListener().OnBeforeConnect();
            }

            TopDictionary param = new TopDictionary();

            param.Add(StreamConstants.PARAM_APPKEY, cometReq.GetAppkey());
            if (!String.IsNullOrEmpty(cometReq.GetUserId()))
            {
                param.Add(StreamConstants.PARAM_USERID, cometReq.GetUserId());
            }
            if (!String.IsNullOrEmpty(cometReq.GetConnectId()))
            {
                param.Add(StreamConstants.PARAM_CONNECT_ID, cometReq.GetConnectId());
            }
            param.Add(StreamConstants.PARAM_TIMESTAMP, DateTime.Now.Ticks);

            IDictionary <string, string> otherParam = cometReq.GetOtherParam();

            if (otherParam != null && otherParam.Count > 0)
            {
                IEnumerator <KeyValuePair <string, string> > kvps = otherParam.GetEnumerator();
                while (kvps.MoveNext())
                {
                    param.Add(kvps.Current.Key, kvps.Current.Value);
                }
            }

            string sign = null;

            try
            {
                sign = TopUtils.SignTopRequest(param, cometReq.GetSecret(), true);
                if (String.IsNullOrEmpty(sign))
                {
                    throw new Exception("Get sign error");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            param.Add(StreamConstants.PARAM_SIGN, sign);
            HttpClient   httpClient = new HttpClient(conf, param);
            HttpResponse response;

            response = httpClient.Post();
            return(currentStreamImpl = new MessageStreamImpl(msgConsumeFactory, response, cometMessageListener, this));
        }
        private void doConnect(string uri)
        {
            var headers  = new Dictionary <string, string>();
            var headers2 = new Dictionary <string, object>();

            headers.Add(APP_KEY, this._id.AppKey);
            headers2.Add(APP_KEY, headers[APP_KEY]);
            headers.Add(GROUP_NAME, this._id.GroupName);
            headers2.Add(GROUP_NAME, headers[GROUP_NAME]);
            headers.Add(TIMESTAMP, DateTime.Now.Ticks.ToString());
            headers2.Add(TIMESTAMP, headers[TIMESTAMP]);
            headers2.Add(SIGN, TopUtils.SignTopRequest(headers, this._appSecret, true));
            this._serverProxy = this._endpoint.GetEndpoint(new TmcServerIdentity(), uri, headers2);
            this._uri         = uri;
            this.Log.InfoFormat("connected to tmc server: {0}", uri);
        }
Example #5
0
        public T Execute <T>(AliSdk.Top.Api.Request.ITopRequest request, AliSdk.Top.Api.parser.ITopParser <T> parser, bool signature, string access_token)
        {
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add("timestamp", DateTime.Now);

            //是否需要用户授权令牌
            if (!string.IsNullOrEmpty(access_token))
            {
                txtParams.Add("access_token", access_token);
            }

            //添加签名参数,不同请求版本不同
            string urlPath = string.Format("{0}/{1}/{2}/{3}/{4}", FORMAT, request.GetVersion(),
                                           NAMESPACE, request.GetApiName(), this.appKey);

            if (signature)
            {
                txtParams.Add("_aop_signature", TopUtils.SignTopRequest(urlPath, txtParams, appSecret));
            }

            //url
            string serverUrl = string.Format("{0}/{1}", this.url, urlPath);

            //if (request.GetApiName().Equals("trade.order.batch.rate"))
            //{
            //    TradeRateParam map = new TradeRateParam();
            //    map.Content = txtParams["content"].ToString();
            //    map.StarLevel = txtParams["starLevel"].ToString();

            //    string mapstr = Newtonsoft.Json.JsonConvert.SerializeObject(map);

            //    txtParams.Add("orders", mapstr);

            //    txtParams.Remove("content");
            //    txtParams.Remove("starLevel");
            //}


            string response;

            response = WebUtils.DoPost(serverUrl, txtParams);

            return(parser.Parse(response));
        }
        public T Execute <T>(ITopRequest <T> request, string session) where T : TopResponse
        {
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, "top-sdk-net-20110512");
            txtParams.Add(TIMESTAMP, DateTime.Now);
            txtParams.Add(SESSION, session);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret));

            // 是否需要上传文件
            string body;

            if (request is ITopUploadRequest <T> )
            {
                ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl, txtParams);
            }

            T rsp;

            if (FORMAT_XML.Equals(format))
            {
                ITopParser <T> tp = new TopXmlParser <T>();
                rsp = tp.Parse(body);
            }
            else
            {
                ITopParser <T> tp = new TopJsonParser <T>();
                rsp = tp.Parse(body);
            }

            return(rsp);
        }
Example #7
0
        private void doConnect(string uri)
        {
            var signHeader = new Dictionary <string, string>();
            var connHeader = new Dictionary <string, object>();

            signHeader.Add(APP_KEY, this._id.AppKey);
            connHeader.Add(APP_KEY, signHeader[APP_KEY]);
            signHeader.Add(GROUP_NAME, this._id.GroupName);
            connHeader.Add(GROUP_NAME, signHeader[GROUP_NAME]);
            signHeader.Add(TIMESTAMP, DateTime.Now.Ticks.ToString());
            connHeader.Add(TIMESTAMP, signHeader[TIMESTAMP]);
            connHeader.Add(SIGN, TopUtils.SignTopRequest(signHeader, this._appSecret, true));
            //extra fields
            connHeader.Add(SDK, DefaultTopClient.SDK_VERSION);
            this._serverProxy = this._endpoint.GetEndpoint(new TmcServerIdentity(), uri, connHeader);
            this._uri         = uri;
            this.Log.InfoFormat("connected to tmc server: {0}", uri);
        }
Example #8
0
        private void doConnect(string uri)
        {
            var signHeader = new Dictionary <string, string>();
            var connHeader = new Dictionary <string, object>();

            signHeader.Add(Constants.APP_KEY, this._id.AppKey);
            connHeader.Add(Constants.APP_KEY, signHeader[Constants.APP_KEY]);

            signHeader.Add(GROUP_NAME, this._id.GroupName);
            connHeader.Add(GROUP_NAME, signHeader[GROUP_NAME]);

            signHeader.Add(Constants.TIMESTAMP, DateTime.Now.Ticks.ToString());
            connHeader.Add(Constants.TIMESTAMP, signHeader[Constants.TIMESTAMP]);

            connHeader.Add(Constants.SIGN, TopUtils.SignTopRequest(signHeader, this._appSecret, Constants.SIGN_METHOD_MD5));
            //extra fields
            connHeader.Add(SDK, Constants.SDK_VERSION);
            connHeader.Add(INTRANET_IP, TopUtils.GetIntranetIp());
            this._serverProxy = this._endpoint.GetEndpoint(new TmcServerIdentity(), uri, connHeader);
            this._uri         = uri;
            this.Log.Info("connected to tmc server: {0}", uri);
        }
Example #9
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            long start = DateTime.Now.Ticks;

            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(Constants.METHOD, request.GetApiName());
            txtParams.Add(Constants.VERSION, "2.0");
            txtParams.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
            txtParams.Add(Constants.APP_KEY, appKey);
            txtParams.Add(Constants.FORMAT, format);
            txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
            txtParams.Add(Constants.TIMESTAMP, timestamp);
            txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            txtParams.Add(Constants.SESSION, session);
            txtParams.AddAll(this.systemParameters);

            if (this.useSimplifyJson)
            {
                txtParams.Add(Constants.SIMPLIFY, "true");
            }

            // 添加签名参数
            txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, appSecret, Constants.SIGN_METHOD_HMAC));

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
            string reqUrl        = WebUtils.BuildRequestUrl(realServerUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        ITopParser <T> tp = new TopXmlParser <T>();
                        rsp = tp.Parse(body);
                    }
                    else
                    {
                        ITopParser <T> tp;
                        if (useSimplifyJson)
                        {
                            tp = new TopSimplifyJsonParser <T>();
                        }
                        else
                        {
                            tp = new TopJsonParser <T>();
                        }
                        rsp = tp.Parse(body);
                    }
                }

                // 追踪错误的请求
                if (rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
                }
                return(rsp);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
Example #10
0
        private T DoExecute <T>(QimenRequest <T> request, string session) where T : QimenResponse
        {
            long start = DateTime.Now.Ticks;

            // 添加协议级请求参数
            TopDictionary parameters = new TopDictionary();

            if (request.GetQueryParameters() != null)
            {
                parameters.AddAll(request.GetQueryParameters());
            }

            parameters.Add(Constants.METHOD, request.GetApiName());
            parameters.Add(Constants.VERSION, request.Version);
            parameters.Add(Constants.APP_KEY, appKey);
            parameters.Add(Constants.TIMESTAMP, request.Timestamp);
            parameters.Add(Constants.FORMAT, format);
            parameters.Add(Constants.SIGN_METHOD, signMethod);
            parameters.Add(Constants.SESSION, session);
            parameters.Add(Constants.PARTNER_ID, Constants.SDK_VERSION);
            parameters.Add(Constants.QM_CUSTOMER_ID, request.CustomerId);

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.AddHeaderParameter(Constants.ACCEPT_ENCODING, Constants.CONTENT_ENCODING_GZIP);
            }

            try
            {
                string reqBody = request.Body;
                if (string.IsNullOrEmpty(reqBody))
                {
                    XmlWriter writer = new XmlWriter(Constants.QM_ROOT_TAG_REQ, typeof(QimenRequest <T>));
                    reqBody = writer.Write(request);
                }

                // 添加签名参数
                parameters.Add(Constants.SIGN, TopUtils.SignTopRequest(parameters, reqBody, appSecret, signMethod));

                string fullUrl = WebUtils.BuildRequestUrl(serverUrl, parameters);
                string rspBody = webUtils.DoPost(fullUrl, Encoding.UTF8.GetBytes(reqBody), Constants.QM_CONTENT_TYPE, request.GetHeaderParameters());

                // 解释响应结果
                T rsp = null;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = rspBody;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        ITopParser <T> tp = new QimenXmlParser <T>();
                        rsp = tp.Parse(rspBody);
                    }
                }

                // 追踪错误的请求
                if (rsp != null && rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, request.GetApiName(), serverUrl, parameters, latency.TotalMilliseconds, rspBody);
                }
                return(rsp);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, request.GetApiName(), serverUrl, parameters, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(SIGN_METHOD, Constants.SIGN_METHOD_MD5);
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, GetSdkVersion());
            txtParams.Add(TIMESTAMP, timestamp);
            txtParams.Add(TARGET_APP_KEY, request.GetTargetAppKey());
            txtParams.Add(SESSION, session);
            txtParams.AddAll(this.systemParameters);

            if (this.useSimplifyJson)
            {
                txtParams.Add(SIMPLIFY, "true");
            }

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret, true));

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
            string reqUrl        = webUtils.BuildGetUrl(realServerUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (FORMAT_XML.Equals(format))
                    {
                        ITopParser tp = new TopXmlParser();
                        rsp = tp.Parse <T>(body);
                    }
                    else
                    {
                        ITopParser tp;
                        if (useSimplifyJson)
                        {
                            tp = new TopJsonSimplifyParser();
                        }
                        else
                        {
                            tp = new TopJsonParser();
                        }
                        rsp = tp.Parse <T>(body);
                    }
                }

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                return(rsp);
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
        private T DoExecute <T>(IQimenCloudRequest <T> request, string session, DateTime timestamp) where T : QimenCloudResponse
        {
            long start = DateTime.Now.Ticks;

            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 兼容 老奇门1.0 的 XML BODY
            String apiBody = null;

            Object[] requestXmlBodyType = request.GetType().GetCustomAttributes(typeof(RequestXmlBodyAttribute), false);
            Boolean  isXmlBody          = (requestXmlBodyType != null && requestXmlBodyType.Length > 0);

            if (isXmlBody)
            {
                XmlWriter writer = new XmlWriter(Constants.QM_ROOT_TAG_REQ, typeof(IQimenCloudRequest <T>));
                apiBody = writer.Write(request);
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(Constants.METHOD, request.GetApiName());
            txtParams.Add(Constants.SIGN_METHOD, signMethod);
            txtParams.Add(Constants.APP_KEY, appKey);
            txtParams.Add(Constants.FORMAT, format);
            txtParams.Add(Constants.VERSION, "2.0");
            txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
            txtParams.Add(Constants.TIMESTAMP, timestamp);
            txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            txtParams.Add(Constants.SESSION, session);
            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            if (isXmlBody)
            {
                txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, apiBody, appSecret, signMethod));
            }
            else
            {
                txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, appSecret, signMethod));
            }

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);

            string reqUrl;

            if (isXmlBody)
            {
                reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
            }
            else
            {
                reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
            }

            try
            {
                string body;
                if (isXmlBody)
                {
                    body = webUtils.DoPost(reqUrl, Encoding.UTF8.GetBytes(apiBody), Constants.QM_CONTENT_TYPE, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp            = Activator.CreateInstance <T>();
                    rsp.Body       = body;
                    rsp.RequestUrl = reqUrl;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        ITopParser <T> tp = new QimenCloudXmlParser <T>();
                        rsp = tp.Parse(body);
                    }
                    else
                    {
                        ITopParser <T> tp = new QimenCloudSimplifyJsonParser <T>();
                        rsp = tp.Parse(body);
                    }
                    rsp.RequestUrl = reqUrl;
                }

                // 追踪错误的请求
                if (rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
                }
                return(rsp);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
        private T DoExecute <T>(ITopRequest <T> request, string session, long timestamp) where T : YunResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (YunException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            var txtParams = new YunDictionary(request.GetParameters())
            {
                { METHOD, request.GetApiName() },
                { VERSION, "1.0" },
                { APP_KEY, appKey },
                { FORMAT, format },
                { TIMESTAMP, timestamp },
                { SESSION, session }
            };

            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret, "UTF-8"));

            var reqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    var uRequest   = (ITopUploadRequest <T>)request;
                    var fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
                }
                else
                {
                    body = webUtils.DoPost(this.serverUrl, txtParams);
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (FORMAT_XML.Equals(format))
                    {
                        ITopParser tp = new TopXmlParser();
                        rsp = tp.Parse <T>(body);
                    }
                    else
                    {
                        ITopParser tp = new TopJsonParser();
                        rsp = tp.Parse <T>(body);
                        //rsp = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(body);
                        //rsp = JsonDeserialize<T>(body);
                    }
                }

                rsp.ReqUrl = reqUrl;

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    var sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                return(rsp);
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    var sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
Example #14
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(createErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, "top-sdk-net-20130425");
            txtParams.Add(TIMESTAMP, timestamp);
            txtParams.Add(SESSION, session);
            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret));

            // 是否需要上传文件
            string body;

            if (request is ITopUploadRequest <T> )
            {
                ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl, txtParams);
            }

            // 解释响应结果
            T rsp;

            if (disableParser)
            {
                rsp      = Activator.CreateInstance <T>();
                rsp.Body = body;
            }
            else
            {
                if (FORMAT_XML.Equals(format))
                {
                    ITopParser tp = new TopXmlParser();
                    rsp = tp.Parse <T>(body);
                }
                else
                {
                    ITopParser tp = new TopJsonParser();
                    rsp = tp.Parse <T>(body);
                }
            }

            // 追踪错误的请求
            if (!disableTrace)
            {
                rsp.ReqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);
                if (rsp.IsError)
                {
                    topLogger.Warn(rsp.ReqUrl + "\r\n" + rsp.Body);
                }
            }

            return(rsp);
        }
Example #15
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            long start = DateTime.Now.Ticks;

            TopBatchRequest batchRequest = request as TopBatchRequest;
            List <ITopRequest <TopResponse> > requestList = batchRequest.RequestList;

            if (requestList == null || requestList.Count == 0)
            {
                throw new TopException("40", "client-error:api request list is empty");
            }

            // 本地校验请求参数
            if (batchRequest.PublicParams == null || batchRequest.PublicParams.Count == 0)
            {
                for (int i = 0; i < requestList.Count; i++)
                {
                    try
                    {
                        requestList[i].Validate();
                    }
                    catch (TopException e)
                    {
                        return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
                    }
                }
            }

            // 添加协议级请求参数
            TopDictionary parameters = new TopDictionary();

            parameters.Add(Constants.VERSION, "2.0");
            parameters.Add(Constants.APP_KEY, appKey);
            parameters.Add(Constants.TIMESTAMP, timestamp);
            parameters.Add(Constants.FORMAT, format);
            parameters.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
            parameters.Add(Constants.PARTNER_ID, GetSdkVersion());
            parameters.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            parameters.Add(Constants.SESSION, session);
            if (Constants.FORMAT_JSON.Equals(format) && this.useSimplifyJson)
            {
                parameters.Add(Constants.SIMPLIFY, "true");
            }

            // 添加自定义分隔符
            string separator = BATCH_API_DEFAULT_SPLIT;

            if (!string.IsNullOrEmpty(batchApiSeparator))
            {
                batchRequest.AddHeaderParameter(BATCH_API_HEADER_SPLIT, separator = batchApiSeparator);
            }

            // 是否需要压缩响应
            if (this.useGzipEncoding)
            {
                batchRequest.AddHeaderParameter(Constants.ACCEPT_ENCODING, Constants.CONTENT_ENCODING_GZIP);
            }

            try
            {
                // 添加公共请求头
                if (!string.IsNullOrEmpty(batchRequest.PublicMethod))
                {
                    batchRequest.AddPublicParam(Constants.METHOD, batchRequest.PublicMethod);
                }
                else
                {
                    if (IsSameRequest(requestList))
                    {
                        batchRequest.AddPublicParam(Constants.METHOD, requestList[0].GetApiName());
                    }
                }

                // 构建批量请求主体
                StringBuilder requestBody    = new StringBuilder();
                string        publicParamStr = WebUtils.BuildQuery(batchRequest.PublicParams);
                if (!string.IsNullOrEmpty(publicParamStr))
                {
                    requestBody.Append(BATCH_API_PUBLIC_PARAMETER).Append(publicParamStr).Append(separator);
                }

                // 组装每个API的请求参数
                for (int i = 0; i < requestList.Count; i++)
                {
                    ITopRequest <TopResponse> bRequest = requestList[i];
                    bRequest.SetBatchApiOrder(i);
                    IDictionary <string, string> apiParams = bRequest.GetParameters();
                    // 如果单个API的方法和批量API的公共方法不一致,那么需要设置单个API的方法名称
                    if (!string.IsNullOrEmpty(bRequest.GetApiName()) && !bRequest.GetApiName().Equals(batchRequest.PublicMethod))
                    {
                        apiParams.Add(Constants.METHOD, bRequest.GetApiName());
                    }
                    if (!string.IsNullOrEmpty(request.GetBatchApiSession()))
                    {
                        apiParams.Add(Constants.SESSION, bRequest.GetBatchApiSession());
                    }
                    if (!string.IsNullOrEmpty(request.GetTargetAppKey()))
                    {
                        apiParams.Add(Constants.TARGET_APP_KEY, bRequest.GetTargetAppKey());
                    }

                    string apiParamStr = WebUtils.BuildQuery(apiParams);
                    if (string.IsNullOrEmpty(apiParamStr))
                    {
                        apiParamStr = "N";
                    }
                    requestBody.Append(apiParamStr);
                    if (i != requestList.Count - 1)
                    {
                        requestBody.Append(separator);
                    }
                }

                string apiBody = requestBody.ToString();

                // 添加签名参数
                parameters.Add(Constants.SIGN, TopUtils.SignTopRequest(parameters, apiBody, appSecret, Constants.SIGN_METHOD_HMAC));

                // 发起批量请求
                string fullUrl = WebUtils.BuildRequestUrl(this.batchServerUrl, parameters);
                string rsp     = webUtils.DoPost(fullUrl, Encoding.UTF8.GetBytes(apiBody), BATCH_API_CONTENT_TYPE, batchRequest.GetHeaderParameters());

                // 构造响应解释器
                ITopParser <TopResponse> parser = null;
                if (Constants.FORMAT_XML.Equals(format))
                {
                    parser = new TopXmlParser <TopResponse>();
                }
                else
                {
                    if (this.useSimplifyJson)
                    {
                        parser = new TopSimplifyJsonParser <TopResponse>();
                    }
                    else
                    {
                        parser = new TopJsonParser <TopResponse>();
                    }
                }

                // 解释响应结果
                TopBatchResponse batchResponse = new TopBatchResponse();
                batchResponse.Body = rsp;

                string[] responseArray = batchResponse.Body.Split(new string[] { separator }, StringSplitOptions.None);
                // 批量API在走单通道验证时没通过,如前面验证,此时只有一个报错信息
                if (responseArray.Length > 0 && responseArray.Length != requestList.Count)
                {
                    TopResponse tRsp = parser.Parse(responseArray[0], requestList[0].GetType().BaseType.GetGenericArguments()[0]);
                    batchResponse.ErrCode    = tRsp.ErrCode;
                    batchResponse.ErrMsg     = tRsp.ErrMsg;
                    batchResponse.SubErrCode = tRsp.SubErrCode;
                    batchResponse.SubErrMsg  = tRsp.SubErrMsg;
                }
                else
                {
                    for (int i = 0; i < responseArray.Length; i++)
                    {
                        TopResponse tRsp = parser.Parse(responseArray[i], requestList[i].GetType().BaseType.GetGenericArguments()[0]);
                        tRsp.Body = responseArray[i];
                        batchResponse.AddResponse(tRsp);
                    }
                }

                if (batchResponse.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, "BatchApi", batchServerUrl, parameters, latency.TotalMilliseconds, batchResponse.Body);
                }

                return(batchResponse as T);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, "BatchApi", batchServerUrl, parameters, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }