Пример #1
0
        public APIResponse <T> PerformRequest <T>(IAPIRequest request) where T : new()
        {
            RestClient client      = new RestClient(request.domain);
            var        restRequest = new RestRequest(request.endpoint, request.httpMethod);

            restRequest.AddParameter("api_key", apiKey);

            if (request.parameters != null)
            {
                foreach (var parameter in request.parameters)
                {
                    restRequest.AddParameter(parameter.Key, parameter.Value);
                }
            }


            IRestResponse <T> parsedResponse = client.Execute <T>(restRequest);

            if (parsedResponse.Data != null && parsedResponse.StatusCode == HttpStatusCode.OK)
            {
                return(new APIResponse <T>(parsedResponse.Data, true));
            }

            return(new APIResponse <T>(default(T), false));
        }
Пример #2
0
 public T Accept(string id)
 {
     _id              = id;
     _request         = buildRequest(_id);
     _responseJObject = _getResponseJObject();
     return(responseToResult(_responseJObject));
 }
Пример #3
0
 /// <summary>
 /// API调用接口通用方法
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="request"></param>
 /// <returns></returns>
 public T Execute <T>(IAPIRequest <T> request) where T : APIResponse
 {
     try
     {
         var tryTimes = 0;
         while (tryTimes < 3)
         {
             T t = null;
             try
             {
                 t = DoExcute(request);
             }
             catch { }
             if (t != null)
             {
                 return(t);
             }
             tryTimes++;
             //_log.Info("error, request is retrying " + tryTimes);
             Thread.Sleep(1000);
         }
         throw new Exception("have tried 3 times, failure request!");
     }
     catch (Exception ex)
     {
         //_log.Error(ex.Message);
         //_log.Error(ex.StackTrace);
         throw new Exception("Request Excuete error.");
     }
 }
Пример #4
0
 private T DoExcute <T>(IAPIRequest <T> request) where T : APIResponse
 {
     try
     {
         // 构建请求地址
         string requestUrl = string.Empty;
         if (!string.IsNullOrEmpty(request.ApiWXRequestSample))
         {
             requestUrl = request.ApiWXRequestSample;
         }
         else
         {
             requestUrl = request.ApiRequestSample.Replace("%BASE_REST_URL%", apiUrl);
         }
         // request
         request.PrepareParam();
         var body   = string.Empty;
         var method = request.RequestMethod.ToLower();
         if (!request.IsJsonRequest)
         {
             if (method == "post")
             {
                 body = webUtil.DoPost(requestUrl, request.RequestBodyDictionary);
             }
             else if (method == "get")
             {
                 body = webUtil.DoGet(requestUrl, request.RequestBodyDictionary);
             }
         }
         else
         {
             var json = request.GetParamJson();
             body = webUtil.DoJsonRequest(requestUrl, json, request.RequestMethod, request.Token);
         }
         // process response
         T rsp;
         if (DisableParser)
         {
             rsp      = Activator.CreateInstance <T>();
             rsp.Body = body;
         }
         else
         {
             // json convert
             IParser <T> parser = new JsonParser <T>();
             rsp = parser.Parse(body);
         }
         return(rsp);
     }
     catch (Exception ex)
     {
         //_log.Error(ex.Message);
         //_log.Error(ex.StackTrace);
         return(null);
     }
 }
Пример #5
0
        public async Task <T> ExecuteAsync <T>(IAPIRequest <T> request) where T : class
        {
            request.Validate();
            string     url        = _GenerateUrl(request.GetUrl(), request.GetUrlParameters());
            HttpMethod httpMethod = request.GetHttpMethod();
            IDictionary <string, string> headers = request.GetRequestHeaders();

            HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;

            //Add http headers
            if (headers != null && headers.Count > 0)
            {
                foreach (var header in headers)
                {
                    webRequest.Headers[header.Key] = header.Value;
                }
            }

            //Execute the request and get response body.
            string body = null;

            try
            {
                HttpWebResponse response;
                switch (httpMethod)
                {
                case HttpMethod.GET:
                    webRequest.Method = "GET";
                    response          = (HttpWebResponse)(await webRequest.GetResponseAsync());
                    break;

                case HttpMethod.POST:
                    webRequest.Method      = "POST";
                    webRequest.ContentType = "application/json; charset=utf-8";
                    var forms = request.GetRequestStream();
                    using (Stream stream = await webRequest.GetRequestStreamAsync())
                    {
                        if (forms != null)
                        {
                            foreach (byte b in forms)
                            {
                                stream.WriteByte(b);
                            }
                        }
                        response = (HttpWebResponse)(await webRequest.GetResponseAsync());
                    }
                    break;

                case HttpMethod.PUT:
                    webRequest.Method = "PUT";
                    response          = (HttpWebResponse)(await webRequest.GetResponseAsync());
                    break;

                case HttpMethod.DELETE:
                    webRequest.Method = "DELETE";
                    response          = (HttpWebResponse)(await webRequest.GetResponseAsync());
                    break;

                default:
                    throw new QDotAPIClientException(string.Format(ErrorMessages.InvalidHTTPMethod, httpMethod.ToString()));
                }

                using (response)
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            body = await reader.ReadToEndAsync();
                        }
                    }
            }
            catch (WebException)
            {
                //Let the client handle the web exception
                throw;
            }
            catch (Exception exception)
            {
                throw new QDotAPIClientException(string.Format(ErrorMessages.GeneralErrorForUrl, httpMethod, url), exception);
            }

            //Parse response body
            if (string.IsNullOrEmpty(body))
            {
                return(null);
            }

            try
            {
                return(JsonConvert.DeserializeObject <T>(body));
            }
            catch (Exception exception)
            {
                throw new QDotAPIClientException(ErrorMessages.ErrorParsingJsonResponse, exception);
            }
        }
Пример #6
0
        public IEnumerable <IAPIResponse> Call(IAPIRequest request)
        {
            //Stopwatch stopWatch = new Stopwatch();
            var pageCounter = request.Page;
            var canRun      = true;
            var client      = _clientFactory.CreateClient();

            var requestUrl = $"{_apiSettings.ApiUrl}/{_apiSettings.ApiKey}/?type={RequestType.Koop.ToString().ToLower()}";

            if (request.SearchFilters != null && request.SearchFilters.Count > 0)
            {
                requestUrl = $"{requestUrl}&zo=/{string.Join("/", request.SearchFilters)}";
            }
            requestUrl = $"{requestUrl}&pagesize={request.PageSize}";

            var uriBuilder  = new UriBuilder(requestUrl);
            var httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{requestUrl}&page={pageCounter}");

            //stopWatch.Start();
            do
            {
                //TODO: make it async
                var task = client.SendAsync(httpRequest);
                task.Wait();
                var response = task.Result;

                var result = HandleResponse(response);
                if (result.Status.Type == APIReturnStatusType.Success)
                {
                    yield return(result);
                }
                else if (result.Status.Type == APIReturnStatusType.Error)
                {
                    throw new Exception(result.Status.ErrorMessage);
                }

                if (result.Status.Type == APIReturnStatusType.LimitExceeeded)
                {
                    Thread.Sleep(_maxRequestsCap);
                    httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{requestUrl}&page={pageCounter}");
                    canRun      = true;
                }
                else if (result?.Paging?.TotalPages > pageCounter)
                {
                    pageCounter += 1;
                    httpRequest  = new HttpRequestMessage(HttpMethod.Get, $"{requestUrl}&page={pageCounter}");
                    canRun       = true;
                }
                else
                {
                    canRun = false;
                }


                //if (pageCounter % 95 == 0 && stopWatch.ElapsedMilliseconds < 60000) //// 60 seconds per ~95 request
                //{
                //    Thread.Sleep(_maxRequestsCap - (int)stopWatch.ElapsedMilliseconds);
                //    stopWatch.Reset();
                //}
            } while (canRun);
        }