示例#1
0
        public Client(IHttpClientFactory clientFactory, IRequestGenerator requestGenerator, Options options)
        {
            _options = options;
            IRequestExecuter requestExecuter = new RequestExecuter(
                clientFactory.CreateHttpClient(new HttpClientOptions
            {
                AddTokenToRequests     = true,
                TokenRetriever         = () => _options.AccessToken,
                ReadRequestsPerSecond  = options.ReadRequestsPerSecond,
                WriteRequestsPerSecond = options.WriteRequestsPerSecond,
            }),
                clientFactory.CreateHttpClient(new HttpClientOptions()));

            if (options.AutoRetry)
            {
                requestExecuter = new AutoRetryRequestExecuter(requestExecuter)
                {
                    NumberOfRetries = options.NumberOfRetries
                };
            }

            RequestGenerator = requestGenerator;

            Core     = new Core(requestExecuter, requestGenerator.Core, options);
            Business = new Business(requestExecuter, requestGenerator);
        }
示例#2
0
        public Client(IHttpClientFactory clientFactory, IRequestGenerator requestGenerator, Options options)
        {
            _options = options;
            IRequestExecuter requestExecuter = new RequestExecuter(
                clientFactory.CreateHttpClient(new HttpClientOptions
                    {
                        AddTokenToRequests = true,
                        TokenRetriever = () => _options.AccessToken,
                        ReadRequestsPerSecond = options.ReadRequestsPerSecond,
                        WriteRequestsPerSecond = options.WriteRequestsPerSecond,
                    }),
                clientFactory.CreateHttpClient(new HttpClientOptions()));

            if (options.AutoRetry)
            {
                requestExecuter = new AutoRetryRequestExecuter(requestExecuter)
                    {
                        NumberOfRetries = options.NumberOfRetries
                    };
            }

            RequestGenerator = requestGenerator;

            Core = new Core(requestExecuter, requestGenerator.Core, options);
            Business = new Business(requestExecuter, requestGenerator, options);
        }
示例#3
0
        public Client(IHttpClientFactory clientFactory, IRequestGenerator requestGenerator, Options options)
        {
            _options = options;

            _clientOAuth = clientFactory.CreateHttpClient(new HttpClientOptions());
            _clientContent = clientFactory.CreateHttpClient(new HttpClientOptions {AddTokenToRequests = true, TokenRetriever = () => _options.AccessToken});
            _clientContentNoRedirection = clientFactory.CreateHttpClient(new HttpClientOptions {AllowAutoRedirect = false, AddTokenToRequests = true, TokenRetriever = () => _options.AccessToken});


            RequestGenerator = requestGenerator;
        }
示例#4
0
        public Client(IHttpClientFactory clientFactory, IRequestGenerator requestGenerator, Options options)
        {
            _options = options;

            _clientOAuth   = clientFactory.CreateHttpClient(new HttpClientOptions());
            _clientContent = clientFactory.CreateHttpClient(new HttpClientOptions {
                AddTokenToRequests = true, TokenRetriever = () => _options.AccessToken
            });
            _clientContentNoRedirection = clientFactory.CreateHttpClient(new HttpClientOptions {
                AllowAutoRedirect = false, AddTokenToRequests = true, TokenRetriever = () => _options.AccessToken
            });


            RequestGenerator = requestGenerator;
        }
 private async Task RequestTriggerPullAsync()
 {
     using (var httpClient = httpClientFactory.CreateHttpClient())
     {
         httpClient.BaseAddress = baseUri;
         await httpClient.PostAsync("v1/Trigger/Pull", null);
     }
 }
示例#6
0
        private async Task <string> SendGetAsync(Uri requestUri)
        {
            using (var httpClient = _httpClientFactory.CreateHttpClient())
            {
                using (var response = await httpClient.GetAsync(requestUri))
                {
                    var responseBody = await response.Content.ReadAsStringAsync();

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

                    var exceptionMessage = $"Could not get data from {requestUri.AbsoluteUri}. Response: {responseBody}";
                    throw new Exception(exceptionMessage);
                }
            }
        }
示例#7
0
 public GoogleTextToSpeechProvider(Settings settings, IHttpClientFactory httpClientFactory = null)
 {
     Settings           = settings;
     _httpClientFactory = httpClientFactory ?? new HttpClientFactory();
     _httpClient        = _httpClientFactory.CreateHttpClient(new CreateHttpClientArgs()
     {
         GZipEnabled = true
     });
 }
示例#8
0
        public async Task <T> SendGetAsync <T>(string apiName, string url)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateHttpClient(apiName);
                var result     = await httpClient.GetAsync(url);

                if (result.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <T>(result.Content.ReadAsStringAsync().Result));
                }

                return(default(T));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task <TResponse> Put <TResponse>(string url, IEnumerable <KeyValuePair <string, string> > bodyParameter)
            where TResponse : class
        {
            var client   = httpClientFactory.CreateHttpClient();
            var content  = new FormUrlEncodedContent(bodyParameter);
            var response = await client.PutAsync(url, content);

            return(await HandleResponse <TResponse>(response));
        }
示例#10
0
        public async Task <CompaniesHouseClientResponse <CompanySearch> > SearchCompanyAsync(CompanySearchRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var httpClient = _httpClientFactory.CreateHttpClient())
            {
                var requestUri = _companySearchUriBuilder.Build(request);

                var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                var result = await response.Content.ReadAsAsync <CompanySearch>(cancellationToken).ConfigureAwait(false);

                return(new CompaniesHouseClientResponse <CompanySearch>(result));
            }
        }
示例#11
0
        public async Task <Stream> GetViewportStreamAsync(double latitude, double longitude, int width, int height, int zoom)
        {
            var httpClient = _httpClientFactory.CreateHttpClient();

            httpClient.BaseAddress = new Uri("https://maps.googleapis.com/");

            string requestUri = $"maps/api/staticmap?center={latitude},{longitude}&zoom={zoom}&size={width}x{height}&key={ApiKey}";

            _logger.LogDebug($"sending reuest '{requestUri}'");
            HttpResponseMessage responseMessage = await httpClient.GetAsync(requestUri);

            Stream imageStream = await responseMessage.Content.ReadAsStreamAsync();

            return(imageStream);
        }
示例#12
0
        public FcmHttpClient(IFcmClientSettings settings, IJsonSerializer serializer, IHttpClientFactory httpClientFactory, CreateHttpClientArgs httpClientArgs)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.settings   = settings;
            this.client     = httpClientFactory.CreateHttpClient(httpClientArgs);
            this.serializer = serializer;
            this.credential = CreateServiceAccountCredential(httpClientFactory, settings);

            InitializeExponentialBackOff(client, settings);
        }
示例#13
0
        public async Task <CompaniesHouseClientResponse <CompanyFilingHistory> > GetCompanyFilingHistoryAsync(string companyNumber, int startIndex, int pageSize, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var httpClient = _httpClientFactory.CreateHttpClient())
            {
                var requestUri = _companyFilingHistoryUriBuilder.Build(companyNumber, startIndex, pageSize);

                var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);

                // Return a null profile on 404s, but raise exception for all other error codes
                if (response.StatusCode != System.Net.HttpStatusCode.NotFound)
                {
                    response.EnsureSuccessStatusCode();
                }

                CompanyFilingHistory result = response.IsSuccessStatusCode
                    ? await response.Content.ReadAsAsync <CompanyFilingHistory>(cancellationToken).ConfigureAwait(false)
                    : null;

                return(new CompaniesHouseClientResponse <CompanyFilingHistory>(result));
            }
        }
示例#14
0
        private async Task <TokenResponse> MakeTokenRequest(Func <HttpContent> postBody, CancellationToken cancellationToken)
        {
            var client  = _clientFactory.CreateHttpClient(new HttpClientHandler());
            var request = new HttpRequestMessage(HttpMethod.Post, $"{_settings.AuthenticationUrl}/oauth/v2/token")
            {
                Content = postBody()
            };

            using (var response = await client.SendAsync(request, cancellationToken))
            {
                var content = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidOperationException(
                              $"Failed to get authentication token. {response.StatusCode}: {content}");
                }

                return(JsonConvert.DeserializeObject <TokenResponse>(content));
            }
        }
示例#15
0
        public async Task InitConnection(IHttpClientFactory factory, IClientSocketFactory socketFactory)
        {
            //Retained for reconnect later on if needed
            this.socketFactory = socketFactory;
            this.httpFactory   = factory;

            // 1. Establish probe handshake

            #region Socket Handshake

            string sessionId = null;
            var    probeTURl = this.baseHttpUrl + this.probeUrl
                               + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

            var websocketKey = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();

            string initialProbeResponse = null;
            var    httpClient           = factory.CreateHttpClient();

            using (var initialProbeRequest = new HttpRequestMessage(HttpMethod.Get, probeTURl.ToString()))
            {
                try
                {
                    using (var response = await httpClient.SendAsync(initialProbeRequest, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        initialProbeResponse = await response.Content.ReadAsStringAsync();

                        var regex = new Regex(PROBE_RESPONSE_REGEX);
                        var match = regex.Match(initialProbeResponse);

                        var initialProbeJson = JObject.Parse(match.Groups[0].Value);

                        sessionId = initialProbeJson.GetValue("sid").ToString();
                        this.keepaliveTimer.Interval = initialProbeJson.GetValue("pingInterval").ToObject <int>();

                        probeTURl = this.baseHttpUrl + this.probeUrl
                                    + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
                                    + $"&sid={sessionId}";
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var roomRequestMessage = new HttpRequestMessage(HttpMethod.Post, probeTURl))
            {
                var roomRequest = $"15:40{this.roomPath},";
                roomRequestMessage.Content = new StringContent(roomRequest);
                //secondaryProbeRequest.Headers.Add("Content-type", "text/plain;charset=UTF-8");
                roomRequestMessage.Headers.Add("Accept", "*/*");
                roomRequestMessage.Headers.Add("DNT", "1");
                roomRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                roomRequestMessage.Headers.Add("Cookie", $"io={sessionId}");

                try
                {
                    using (var response = await httpClient.SendAsync(roomRequestMessage, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        var ok = await response.Content.ReadAsStringAsync();

                        Debug.Assert(ok.Equals("ok"));
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var protocolUpgradeRequest = new HttpRequestMessage(HttpMethod.Get, probeTURl))
            {
                protocolUpgradeRequest.Headers.Add("DNT", "1");
                protocolUpgradeRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                protocolUpgradeRequest.Headers.Add("Cookie", $"io={sessionId}");
                protocolUpgradeRequest.Headers.Add("Connection", "Upgrade");
                protocolUpgradeRequest.Headers.Add("Pragma", "no-cache");
                protocolUpgradeRequest.Headers.Add("Cache-control", "no-cache");
                protocolUpgradeRequest.Headers.Add("Upgrade", "websocket");
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Version", "13");
                protocolUpgradeRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Key", websocketKey);
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Extensions", "permessage-deflate; client_max_window_bits");

                try
                {
                    using (var response = await httpClient.SendAsync(protocolUpgradeRequest, CancellationToken.None))
                    {
                        if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
                        {
                            throw new HttpRequestException(
                                      "Did not correctly receive protocol switch from server!");
                        }

                        var accept = response.Headers.GetValues("Sec-Websocket-Accept");

                        if (!accept.Any())
                        {
                            throw new HttpRequestException("Did not get Sec-Websocket-Accept header!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var finalHandshake = new HttpRequestMessage(HttpMethod.Get, probeTURl))
            {
                finalHandshake.Headers.Add("Accept", "*/*");
                finalHandshake.Headers.Add("DNT", "1");
                finalHandshake.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                finalHandshake.Headers.Add("Cookie", $"io={sessionId}");
                finalHandshake.Headers.Add("Accept-Encoding", "gzip, deflate, br");

                try
                {
                    using (var response = await httpClient.SendAsync(finalHandshake, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        var finalResponse = await response.Content.ReadAsStringAsync();

                        if (!finalResponse.Equals($"15:40{this.roomPath},"))
                        {
                            throw new HttpRequestException($"Final handshake {finalResponse} response was not expected!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw ex;
                }
            }

            #endregion

            // 2. Upgrade connection and send ping

            this.SocketEndpointUrl = this.baseWsUrl
                                     + websocketQueryParam
                                     + $"&sid={sessionId}";

            this.websocketClient = socketFactory.CreateSocketClient();

            try
            {
                await this.websocketClient.ConnectAsync(new Uri(this.SocketEndpointUrl), CancellationToken.None);
            }
            catch (Exception connectException)
            {
                Console.Error.WriteLine(connectException);
                throw connectException;
            }

            await SendConnectionProbe();

            this.keepaliveTimer.Start();
        }
 public IWorkflowMessageTransport CreateMessageTransport(Uri address)
 {
     return(new WorkflowMessageHttpTransport(_httpClientFactory.CreateHttpClient()));
 }
示例#17
0
        public async ValueTask <HttpResponseMessage> SendAsync(DynamoDbContextConfig config, HttpContent httpContent, CancellationToken cancellationToken = default)
        {
            try
            {
                int internalServerErrorRetries           = 0,
                    limitExceededRetries                 = 0,
                    provisionedThroughputExceededRetries = 0,
                    requestLimitExceededRetries          = 0,
                    serviceUnavailableRetries            = 0,
                    throttlingRetries = 0;
                while (true)
                {
                    TimeSpan delay;
                    try
                    {
                        using var request = new HttpRequestMessage(HttpMethod.Post, config.RegionEndpoint.RequestUri)
                              {
                                  Content = httpContent
                              };

                        try
                        {
                            var httpClient = _httpClientFactory.CreateHttpClient();
                            var stream     = await httpContent.ReadAsStreamAsync().ConfigureAwait(false);

                            var credentials = await config.CredentialsProvider.GetCredentialsAsync(cancellationToken).ConfigureAwait(false);

                            var metadata = new SigningMetadata(config.RegionEndpoint, credentials, DateTime.UtcNow, httpClient.DefaultRequestHeaders,
                                                               httpClient.BaseAddress);
                            AwsRequestSigner.Sign(request, (RecyclableMemoryStream)stream, in metadata);

                            var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                            if (!response.IsSuccessStatusCode)
                            {
                                await ErrorHandler.ProcessErrorAsync(config.Metadata, response, cancellationToken).ConfigureAwait(false);
                            }

                            return(response);
                        }
                        finally
                        {
                            request.Content = null;
                        }
                    }
                    catch (InternalServerErrorException)
                    {
                        if (!config.RetryStrategies.InternalServerErrorStrategy.TryGetRetryDelay(internalServerErrorRetries++, out delay))
                        {
                            throw;
                        }
                    }
                    catch (LimitExceededException)
                    {
                        if (!config.RetryStrategies.LimitExceededStrategy.TryGetRetryDelay(limitExceededRetries++, out delay))
                        {
                            throw;
                        }
                    }
                    catch (ProvisionedThroughputExceededException)
                    {
                        if (!config.RetryStrategies.ProvisionedThroughputExceededStrategy.TryGetRetryDelay(provisionedThroughputExceededRetries++, out delay))
                        {
                            throw;
                        }
                    }
                    catch (RequestLimitExceededException)
                    {
                        if (!config.RetryStrategies.RequestLimitExceededStrategy.TryGetRetryDelay(requestLimitExceededRetries++, out delay))
                        {
                            throw;
                        }
                    }
                    catch (ServiceUnavailableException)
                    {
                        if (!config.RetryStrategies.ServiceUnavailableStrategy.TryGetRetryDelay(serviceUnavailableRetries++, out delay))
                        {
                            throw;
                        }
                    }
                    catch (ThrottlingException)
                    {
                        if (!config.RetryStrategies.ThrottlingStrategy.TryGetRetryDelay(throttlingRetries++, out delay))
                        {
                            throw;
                        }
                    }

                    await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
                }
            }
            finally
            {
                httpContent.Dispose();
            }
        }
示例#18
0
 public GithubApiClient(IHttpClientFactory httpClientFactory)
 {
     _httpClient = httpClientFactory.CreateHttpClient(BaseUrl, MediaTypeHeader, ClientUserAgent);
 }