Exemplo n.º 1
0
        /// <summary>Call the CloudPOS API.</summary>
        /// <param name="uri">The uri to call.</param>
        /// <param name="action">The action to perform.</param>
        /// <param name="jsonToSend">The JSON to send.</param>
        /// <returns>The CallResults.</returns>
        public static CallResults CallAPI(string uri, enumRESTVerb action, string jsonToSend = "")
        {
            CallResults results = new CallResults();

            string appendOrQueryString = uri.Contains("?") ? "&": "?";

            string pagedUrl = string.Format("{0}{1}PageNumber=", uri, appendOrQueryString);

            string nextUrl = uri;

            do
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Constants.API_KEY);

                    StringContent content = new StringContent(jsonToSend, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = GetResponseFromAPI(client, nextUrl, action, content);

                    string data = response.Content.ReadAsStringAsync().Result;

                    if (response.IsSuccessStatusCode == true)
                    {
                        nextUrl = HandlePaging(response, pagedUrl);

                        results.JsonBuilder.Append(data);
                    }
                    else
                    {
                        results.ErrorMessage = data;

                        HandleBadResponse(response, ref nextUrl, ref results);
                    }
                }
            }while (nextUrl != string.Empty);

            results.JsonBuilder.Replace("][", ",");

            return(results);
        }
Exemplo n.º 2
0
        /// <summary>Handles a bad response from the API.</summary>
        /// <param name="response">The response.</param>
        /// <param name="nextUri">[in,out] The next uri to call.</param>
        /// <param name="results">[in,out] The results.</param>
        private static void HandleBadResponse(HttpResponseMessage response, ref string nextUri, ref CallResults results)
        {
            switch (response.StatusCode)
            {
            case HttpStatusCode.NotFound:
                nextUri        = string.Empty;
                results.Status = enumApiCallStatus.NOT_FOUND;
                break;

            case (HttpStatusCode)429:
                Thread.Sleep(1000);
                break;

            case HttpStatusCode.Unauthorized:
                nextUri        = string.Empty;
                results.Status = enumApiCallStatus.NOT_AUTHENTICATED;
                break;

            default:
                nextUri        = string.Empty;
                results.Status = enumApiCallStatus.SERVER_ERROR;
                break;
            }
        }