Esempio n. 1
0
        /// <summary>
        /// Async send the request to the server
        /// </summary>
        /// <returns>Async</returns>
        public async Task <string> SendAsync(DimeloRequest request)
        {
            // only create HttpClient once for performance
            if (_client == null)
            {
                _client = new HttpClient();
            }

            // creating the request
            StringContent content;

            try
            {
                // construct the json content first
                string json = request.GetJson();
                content = new StringContent(json, Encoding.UTF8, MEDIATYPE_JSON);

                // compute the signature
                string signature = SigningHelper.Sign(_accessToken, json);

                // set the necessary header(s)
                _client.DefaultRequestHeaders.Clear();
                _client.DefaultRequestHeaders.Add(SIGNATURE_ATTRIBUTE, signature);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error setting the request to send", ex);
            }

            // send the request
            HttpResponseMessage response = null;

            try
            {
                response = await _client.PostAsync(_endpointUrl, content);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error sending the request to {_endpointUrl}", ex);
            }

            // handle the response
            try
            {
                string responseContent = await response.Content.ReadAsStringAsync();

                // unsuccesful statuscodes are thrown as exception
                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpRequestException($"Sending the request return HTTP status code {(int)response.StatusCode} {response.StatusCode} {responseContent}");
                }
                return(responseContent);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error processing the response", ex);
            }
        }