Exemple #1
0
        protected async Task <T> SendRequest <T>(string methodName, string version, ApiMethodType apiMethod, HttpMethod httpMethod,
                                                 Dictionary <string, string> parameters = null, ResponseParseHandler <T> customHandler = null)
        {
            if ((apiMethod == ApiMethodType.ApiKey && string.IsNullOrEmpty(_apiKey)) ||
                (apiMethod == ApiMethodType.Signed &&
                 (string.IsNullOrEmpty(_apiKey) || string.IsNullOrEmpty(_apiSecret))))
            {
                throw new Exception("You have to instantiate client with proper keys in order to make ApiKey or Signed API requests!");
            }

            if (parameters == null)
            {
                parameters = new Dictionary <string, string>();
            }

            if (apiMethod == ApiMethodType.Signed)
            {
                var timestamp = Util.GetCurrentMilliseconds();
                parameters.Add("timestamp", timestamp.ToString(CultureInfo.InvariantCulture));

                var parameterTextForSignature = GetParameterText(parameters);
                var signedBytes = Util.Sign(_apiSecret, parameterTextForSignature);
                parameters.Add("signature", Util.GetHexString(signedBytes));
            }

            var parameterTextPrefix = parameters.Count > 0 ? "?" : string.Empty;
            var parameterText       = GetParameterText(parameters);

            string response;

            using (var client = new WebClient())
            {
                if (apiMethod == ApiMethodType.Signed || apiMethod == ApiMethodType.ApiKey)
                {
                    client.Headers.Add("X-MBX-APIKEY", _apiKey);
                }

                try
                {
                    var getRequestUrl  = $"{BaseUrl}/{version}/{methodName}{parameterTextPrefix}{parameterText}";
                    var postRequestUrl = $"{BaseUrl}/{version}/{methodName}";

                    response = httpMethod == HttpMethod.Get ?
                               await client.DownloadStringTaskAsync(getRequestUrl) :
                               await client.UploadStringTaskAsync(postRequestUrl, httpMethod.Method, parameterText);
                }
                catch (WebException webException)
                {
                    using (var reader = new StreamReader(webException.Response.GetResponseStream(), Encoding.UTF8))
                    {
                        var errorObject  = JObject.Parse(reader.ReadToEnd());
                        var errorCode    = (int)errorObject["code"];
                        var errorMessage = (string)errorObject["msg"];
                        throw new Exception($"{errorCode}{errorMessage}");
                    }
                }
            }
            return(customHandler != null?customHandler(response) : JsonConvert.DeserializeObject <T>(response));
        }
Exemple #2
0
 public LolApiMethod(LolApiMethodName md, LolApiPath[] array, Type returnValueType, ApiMethodType requestType)
 {
     this.ApiMethodName     = md;
     this.RiotGamesApiPaths = array ?? new LolApiPath[0];
     ReturnValueType        = returnValueType;
     TypesOfQueryParameter  = new Dictionary <string, Type>();
     RequestType            = requestType;
 }
Exemple #3
0
        /// <summary>
        /// Parse the inovked "service" path to determine which method is meant to
        /// be invoked.
        /// </summary>
        /// <param name="request">The current HTTP Request object.</param>
        /// <returns>An ApiMethodType method denoting the invoked web method.</returns>
        /// <remarks>Throws HttpParseException if an invalid path is supplied.</remarks>
        private ApiMethodType ParseApiMethod(HttpRequest request)
        {
            ApiMethodType method = ApiMethodType.Unknown;

            // Get the particular method being invoked by parsing context.Request.PathInfo
            if (string.IsNullOrEmpty(request.PathInfo))
            {
                throw new HttpParseException("Request.Pathinfo is empty.");
            }

            String[] path = Strings.ToListOfTrimmedStrings(request.PathInfo, '/');

            // path[0] -- version
            // path[1] -- Method
            if (path.Length != 2)
            {
                throw new HttpParseException("Unknown path format.");
            }

            // Only version 1 is presently supported.
            if (!string.Equals(path[0], "v1", StringComparison.CurrentCultureIgnoreCase))
            {
                String msg = String.Format(errorVersionFormat, path[0]);
                log.Error(msg);
                throw new HttpParseException(msg);
            }

            // Attempt to retrieve the desired method.
            method = ConvertEnum <ApiMethodType> .Convert(path[1], ApiMethodType.Unknown);

            if (method == ApiMethodType.Unknown)
            {
                String msg = String.Format(errorMethodFormat, path[1]);
                log.Error(msg);
                throw new HttpParseException(msg);
            }

            return(method);
        }
Exemple #4
0
        /// <summary>
        /// Creates an instance of a specific Invoker subclass.  Use this method instead of
        /// trying to directly instantiate an Invoker.
        /// </summary>
        /// <param name="method">An ApiMethodType value corresponding to the Dictionary Service method
        /// to be invoked.</param>
        /// <param name="request">The current HTTP request.</param>
        /// <returns>A dictionary service Invoker object.</returns>
        public static Invoker Create(ApiMethodType method, HttpRequest request)
        {
            Invoker invoker;

            switch (method)
            {
            case ApiMethodType.GetTerm:
                invoker = new GetTermInvoker(request);
                log.Trace("Invoker.Create() - creating GetTermInvoker.");
                break;

            case ApiMethodType.Search:
                invoker = new SearchInvoker(request);
                log.Trace("Invoker.Create() - creating SearchInvoker.");
                break;

            case ApiMethodType.SearchSuggest:
                invoker = new SearchSuggestInvoker(request);
                log.Trace("Invoker.Create() - creating SearchSuggestInvoker.");
                break;

            case ApiMethodType.Expand:
                invoker = new ExpandInvoker(request);
                log.Trace("Invoker.Create() - creating ExpandInvoker.");
                break;

            case ApiMethodType.Unknown:
            default:
            {
                string msg = String.Format("Invoker Create() - Invalid method '{0}' requested.", method);
                log.Error(msg);
                throw new DictionaryException(msg);
            }
            }

            return(invoker);
        }
Exemple #5
0
        /// <summary>
        /// Entry point for handling the HTTP request.  ProcessRequest manages the process of
        /// determining which method was requested, invoking it, and returning a JSON response.
        /// Part of IHttpHandler
        /// </summary>
        /// <param name="context">Object containing the details of current HTTP request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            try
            {
                // Get the particular method being invoked.
                ApiMethodType method = ParseApiMethod(request);

                // Get object for invoking the specific dictionary method.
                Invoker invoker = Invoker.Create(method, request);

                // Invoke the requested dictionary method.
                IJsonizable result = invoker.Invoke();

                // Put together the JSON response.
                Jsonizer json = new Jsonizer(result);

                response.ContentType = "application/json";
                response.Write(json.ToJsonString());
            }
            // There was something wrong with the request that prevented us from
            // being able to invoke a method.
            catch (HttpParseException ex)
            {
                response.Status     = ex.Message;
                response.StatusCode = 400;
            }
            // Something went wrong in our code.
            catch (Exception ex)
            {
                log.ErrorFormat(errorProcessFormat, ex, request.RawUrl);
                response.StatusDescription = "Error processing dictionary request.";
                response.StatusCode        = 500;
            }
        }
 public static ApiMethod GetMethod(ApiMethodType type)
 {
     return(LazyCollection[type].Value);
 }
        /// <summary>
        /// 调用api请求处理
        /// </summary>
        /// <param name="methodType"></param>
        /// <param name="apiUrl"></param>
        /// <param name="postObject"></param>
        /// <param name="token"></param>
        /// <param name="tokenScheme"></param>
        /// <returns></returns>
        private static async Task <string> Load(ApiMethodType methodType, string apiUrl, object postObject, string token = "", string tokenScheme = "Bearer")
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                token = Token;
            }

            HttpClientHandler handler = new HttpClientHandler();

            //handler.Proxy = null;
            //handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (var httpClient = new HttpClient(handler))
            {
                // 设置Token信息
                if (!string.IsNullOrWhiteSpace(token))
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenScheme, token);
                }

                //发送请求
                HttpResponseMessage response = null;
                switch (methodType)
                {
                case ApiMethodType.GET:
                {
                    response = await httpClient.GetAsync(apiUrl);

                    break;
                }

                case ApiMethodType.POST:
                {
                    response = await httpClient.PostAsync(apiUrl, GetJsonContent(postObject));

                    break;
                }

                case ApiMethodType.PUT:
                {
                    response = await httpClient.PutAsync(apiUrl, GetJsonContent(postObject));

                    break;
                }

                case ApiMethodType.DELETE:
                {
                    response = await httpClient.DeleteAsync(apiUrl);

                    break;
                }

                case ApiMethodType.PATCH:
                {
                    HttpRequestMessage requestMessage = new HttpRequestMessage
                    {
                        Method = new HttpMethod("PATCH")
                    };
                    //requestMessage.Headers.Authorization = new AuthenticationHeaderValue(tokenScheme, token);
                    //requestMessage.RequestUri = new Uri(apiUrl);
                    response = await httpClient.SendAsync(requestMessage);

                    break;
                }

                case ApiMethodType.OPTIONS:
                {
                    HttpRequestMessage requestMessage = new HttpRequestMessage
                    {
                        Method  = HttpMethod.Options,
                        Content = GetJsonContent(postObject)
                    };
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue(tokenScheme, token);
                    requestMessage.RequestUri            = new Uri(apiUrl);
                    response = await httpClient.SendAsync(requestMessage);

                    break;
                }

                default:
                {
                    response = await httpClient.PostAsync(apiUrl, GetJsonContent(postObject));

                    break;
                }
                }

                //获取返回值
                if (response != null)
                {
                    return(await response.Content.ReadAsStringAsync());
                }
                else
                {
                    return(String.Empty);
                }
            }
        }
Exemple #8
0
 public LolApiMethod(LolApiMethodName md, LolApiPath[] array, Type returnValueType, ApiMethodType requestType, Type _bodyValueType, bool _isBodyRequired)
     : this(md, array, returnValueType, requestType)
 {
     BodyValueType  = _bodyValueType;
     IsBodyRequired = _isBodyRequired;
 }