示例#1
0
        public async Task <IRestResponse> GetResponseAsync(Method method, Uri uri,
                                                           bool isRequestIntercept  = true,
                                                           bool isResponseIntercept = true, int timeout = 30000, string requestContent = null, string contentType = null,
                                                           IEnumerable <KeyValuePair <string, string> > additionalHeaders = null)
        {
            var client = new RestClient(uri);

            client.Timeout = timeout;
            var request = new RestRequest(Method.POST);
            var context = new CommunicationContext
            {
                Method              = method,
                Uri                 = uri,
                IsRequestIntercept  = isRequestIntercept,
                IsResponseIntercept = isResponseIntercept,
                TimeOut             = timeout,
                RequestContent      = requestContent,
                ContentType         = contentType,
                AdditionalHeaders   = additionalHeaders
            };

            if (this._httpInterceptConfiguration.OnBeforeRequest != null && isRequestIntercept)
            {
                request.OnBeforeRequest = (IHttp http) => {
                    this._httpInterceptConfiguration.OnBeforeRequest(context, http);
                };
            }
            request.AddHeader("Content-Type", contentType ?? "application/json");
            LogHelper.Logger.Info(string.Format("Http Request: \r\n{0}", requestContent));
            if (!string.IsNullOrEmpty(contentType))
            {
                request.AddParameter(contentType ?? "application/json", requestContent, ParameterType.RequestBody);
            }
            if (additionalHeaders != null)
            {
                LogHelper.Logger.Info(string.Format("Http Request Header: \r\n{0}", JsonConvert.SerializeObject(additionalHeaders)));
                foreach (KeyValuePair <string, string> additionHeader in additionalHeaders)
                {
                    request.AddHeader(additionHeader.Key, additionHeader.Value);
                }
            }
            IRestResponse response = await client.ExecuteAsync(request);

            if (!string.IsNullOrEmpty(response.ErrorMessage) || response.ErrorException != null)
            {
                LogHelper.Logger.Error(response.ErrorMessage, response.ErrorException);
            }
            return(response);
        }