Пример #1
0
        public async Task <TResponseType> SendAsync <TResponseType>(HttpRequestMessageBuilder builder, HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            // Add Authorization Header:
            var accessToken = await CreateAccessTokenAsync(cancellationToken).ConfigureAwait(false);

            builder.AddHeader("Authorization", $"Bearer {accessToken}");

            // Build the Request Message:
            var httpRequestMessage = builder.Build();

            // Invoke actions before the Request:
            OnBeforeRequest(httpRequestMessage);

            // Invoke the Request:
            HttpResponseMessage httpResponseMessage = await client
                                                      .SendAsync(httpRequestMessage, completionOption, cancellationToken)
                                                      .ConfigureAwait(false);

            // Invoke actions after the Request:
            OnAfterResponse(httpRequestMessage, httpResponseMessage);

            // Apply the Response Interceptors:
            EvaluateResponse(httpResponseMessage);

            // Now read the Response Content as String:
            string httpResponseContentAsString = await httpResponseMessage.Content
                                                 .ReadAsStringAsync()
                                                 .ConfigureAwait(false);

            // And finally return the Object:
            return(serializer.DeserializeObject <TResponseType>(httpResponseContentAsString));
        }
Пример #2
0
        public TransactionStatus Send(Transaction transaction)
        {
            var requestMessage      = _httpRequestMessageBuilder.Build();
            var responseMessage     = _transactionsClient.Send(requestMessage);
            var transactionResponse = _httpResponseMessageReader.Read <TransactionStatus>(responseMessage);

            return(transactionResponse);
        }
Пример #3
0
        public Task <HttpResponseMessage> Execute(IronClientConfig config, IRestClientRequest request)
        {
            var requestBuilder = new HttpRequestMessageBuilder(config, this, new RestClientRequest
            {
                EndPoint = request.EndPoint,
                Query    = request.Query,
                Method   = request.Method,
                Content  = request.Content
            });

            return(httpClient.SendAsync(requestBuilder.Build()));
        }
Пример #4
0
        public async Task <StateVectorResponse> GetOwnStateVectorsAsync(int?time = null, string icao24 = null, int[] serials = null, Credentials credentials = null, BoundingBox boundingBox = null, CancellationToken cancellationToken = default)
        {
            var url = $"{apiUrl}/states/own";

            var httpRequestMessageBuilder = new HttpRequestMessageBuilder(url, HttpMethod.Get);

            if (time.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("time", time.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (icao24 != null)
            {
                httpRequestMessageBuilder.AddQueryString("icao24", icao24);
            }

            if (serials != null)
            {
                foreach (var serial in serials)
                {
                    httpRequestMessageBuilder.AddQueryString("serials", serial.ToString(CultureInfo.InvariantCulture));
                }
            }

            if (boundingBox != null)
            {
                httpRequestMessageBuilder.AddQueryString("lamin", boundingBox.LaMin.ToString(CultureInfo.InvariantCulture));
                httpRequestMessageBuilder.AddQueryString("lomin", boundingBox.LoMin.ToString(CultureInfo.InvariantCulture));
                httpRequestMessageBuilder.AddQueryString("lamax", boundingBox.LaMax.ToString(CultureInfo.InvariantCulture));
                httpRequestMessageBuilder.AddQueryString("lomax", boundingBox.LoMax.ToString(CultureInfo.InvariantCulture));
            }

            var httpRequestMessage = httpRequestMessageBuilder.Build();

            if (credentials != null)
            {
                SetBasicAuthHeader(httpRequestMessage, credentials);
            }

            using (var httpResponse = await httpClient
                                      .SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                                      .ConfigureAwait(false))
            {
                httpResponse.EnsureSuccessStatusCode();

                using (var stream = await httpResponse.Content
                                    .ReadAsStreamAsync(cancellationToken)
                                    .ConfigureAwait(false))
                {
                    return(await StateVectorResponseParser.ParseAsync(stream));
                }
            }
        }
Пример #5
0
        private HttpResponseMessage AttemptRequest(IronSharpConfig sharpConfig, HttpRequestMessageBuilder requestBuilder, int attempt = 0)
        {
            var request = requestBuilder.Build();

            if (attempt > HttpClientOptions.RetryLimit)
            {
                throw new MaximumRetryAttemptsExceededException(request, HttpClientOptions.RetryLimit);
            }

            ILog logger = LogManager.GetLogger <RestClient>();

            if (logger.IsDebugEnabled)
            {
                using (var sw = new StringWriter())
                {
                    sw.WriteLine("{0} {1}", request.Method, request.RequestUri);
                    if (request.Content != null)
                    {
                        sw.WriteLine(request.Content.ReadAsStringAsync().Result);
                    }
                    logger.Debug(sw.ToString());
                }
            }

            HttpResponseMessage response = httpClient.SendAsync(request).Result;

            if (logger.IsDebugEnabled)
            {
                if (response.Content != null)
                {
                    logger.Debug(response.Content.ReadAsStringAsync().Result);
                }
            }

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }

            if (HttpClientOptions.EnableRetry && IsRetriableStatusCode(response))
            {
                attempt++;

                ExponentialBackoff.Sleep(sharpConfig.BackoffFactor, attempt);

                return(AttemptRequest(sharpConfig, requestBuilder, attempt));
            }

            return(response);
        }
Пример #6
0
        public async Task <TResponseType[]> SendBatchAsync <TResponseType>(HttpRequestMessageBuilder builder, CancellationToken cancellationToken)
        {
            // Add Authorization Header:
            var accessToken = await CreateAccessTokenAsync(cancellationToken).ConfigureAwait(false);

            builder.AddHeader("Authorization", $"Bearer {accessToken}");

            // Build the Request Message:
            var httpRequestMessage = builder.Build();

            // Invoke actions before the Request:
            OnBeforeRequest(httpRequestMessage);

            // Invoke the Request:
            HttpResponseMessage httpResponseMessage = await client
                                                      .SendAsync(httpRequestMessage, cancellationToken)
                                                      .ConfigureAwait(false);

            // Invoke actions after the Request:
            OnAfterResponse(httpRequestMessage, httpResponseMessage);

            // Apply the Response Interceptors:
            EvaluateResponse(httpResponseMessage);

            var multipart = await httpResponseMessage.Content.ReadAsMultipartAsync(cancellationToken);

            List <TResponseType> result = new List <TResponseType>();

            foreach (var content in multipart.Contents)
            {
                string part = await content.ReadAsStringAsync();

                // This is quite a hack approach, which might or might not work for all scenarios.
                // I am splitting the multipart response into lines, which in turn is skipped until
                // we hit a line with a single "{", which indicates we have found some JSON:
                IEnumerable <string> jsonLines = part.Split('\n').SkipWhile(x => !string.Equals(x.Trim(), "{"));

                // Then we turn the lines into a String again:
                var jsonString = string.Join("\n", jsonLines);

                // So Newtonsoft.JSON can deserialize it again:
                var response = serializer.DeserializeObject <TResponseType>(jsonString);

                // And add it to the result:
                result.Add(response);
            }

            // And finally return the Object:
            return(result.ToArray());
        }
Пример #7
0
        public void ShouldCalculateRightUrl(Type contractType, string methodName, string baseAddress, string expectedUrl)
        {
            //Arrange
            var srvDesc = ServiceDescription.Create(contractType);

            var method = contractType.GetMethod(methodName);

            var mDesc = srvDesc.Methods
                        .Where(kv => kv.Key == method.MetadataToken)
                        .Select(kv => kv.Value)
                        .First();

            var reqMsgBuilder = new HttpRequestMessageBuilder(baseAddress, mDesc);

            //Act
            var reqMsg = reqMsgBuilder.Build();

            //Assert
            Assert.Equal(expectedUrl, reqMsg.RequestUri.OriginalString);
        }
Пример #8
0
        public async Task SendAsync(HttpRequestMessageBuilder builder, HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            // Add Authorization Header:
            var accessToken = await CreateAccessTokenAsync(cancellationToken).ConfigureAwait(false);

            builder.AddHeader("Authorization", $"Bearer {accessToken}");

            // Build the Request Message:
            var httpRequestMessage = builder.Build();

            // Invoke actions before the Request:
            OnBeforeRequest(httpRequestMessage);

            // Invoke the Request:
            HttpResponseMessage httpResponseMessage = await client.SendAsync(httpRequestMessage, completionOption, cancellationToken).ConfigureAwait(false);

            // Invoke actions after the Request:
            OnAfterResponse(httpRequestMessage, httpResponseMessage);

            // Apply the Response Interceptors:
            EvaluateResponse(httpResponseMessage);
        }
 public void Build_WhenBuildIsCalledWithoutCreateMessage_ShouldThrowAnInvalidOperationException()
 {
     Assert.Throws <InvalidOperationException>(() => _sut.Build());
 }
Пример #10
0
        public async Task <string> Search(string q, string lang = default, int?limit = default, float?lat = default, float?lon = default, int?location_bias_scale = default, string bbox = default, string[] osm_tags = default, CancellationToken cancellationToken = default)
        {
            var url = $"{applicationOptions.Photon?.ApiUrl}";

            var httpRequestMessageBuilder = new HttpRequestMessageBuilder(url, HttpMethod.Get);

            httpRequestMessageBuilder.AddQueryString("q", q);

            if (!string.IsNullOrWhiteSpace(lang))
            {
                httpRequestMessageBuilder.AddQueryString("lang", lang);
            }

            if (limit.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("limit", limit.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (lat.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("lat", lat.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (lon.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("lon", lon.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (location_bias_scale.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("location_bias_scale", location_bias_scale.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (!string.IsNullOrWhiteSpace(bbox))
            {
                httpRequestMessageBuilder.AddQueryString("bbox", bbox);
            }

            if (osm_tags != null)
            {
                foreach (var osm_tag in osm_tags)
                {
                    httpRequestMessageBuilder.AddQueryString("osm_tag", osm_tag);
                }
            }

            var httpRequestMessage = httpRequestMessageBuilder.Build();

            var httpResponse = await httpClient
                               .SendAsync(httpRequestMessage)
                               .ConfigureAwait(false);

            if (!httpResponse.IsSuccessStatusCode)
            {
                var statusCode = httpResponse.StatusCode;
                var reason     = httpResponse.ReasonPhrase;

                throw new Exception($"API Request failed with Status Code {statusCode} and Reason {reason}. For additional information, see the HttpResponseMessage in this Exception.");
            }

            return(await httpResponse.Content
                   .ReadAsStringAsync()
                   .ConfigureAwait(false));
        }