private static HttpClient CreateDefaultHttpClient()
        {
            HttpClientHandler?handler = null;

            try
            {
                handler = new HttpClientHandler();
                if (handler.SupportsAutomaticDecompression)
                {
                    handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
                }

                if (handler.SupportsRedirectConfiguration)
                {
                    handler.AllowAutoRedirect = true;
                }

                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.UseCookies = false;

                handler.UseDefaultCredentials = false;

                return(new HttpClient(handler));
            }
            catch
            {
                handler?.Dispose();

                throw;
            }
        }
Пример #2
0
        /// <summary>
        /// Schliesst die Verbindung zum Server
        /// </summary>
        /// <param name="disposing">Flag, welches anzeigt, ob das Disposing durchgeführt werden soll</param>
        protected void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (!disposing)
            {
                try
                {
                    client.CancelPendingRequests();
                }
                catch { }

                client.Dispose();
                handler.Dispose();

                IManagementSession[] currentSessions = sessions.Values.ToArray();
                sessions = null;

                foreach (IManagementSession session in currentSessions)
                {
                    session.Dispose();
                }
            }

            disposed = true;
        }
 /// <summary>
 /// Dispose of the HttpClient once the tests are complete.
 /// </summary>
 public void Dispose()
 {
     var response = PostDeleteDisplayFolder().Result;
     response.Dispose();
     _handler.Dispose();
     Client.Dispose();
 }
Пример #4
0
        private static HttpClient CreateDefaultHttpClient()
        {
            HttpClientHandler?handler = null;
            HttpClient?       retVal  = null;

            try
            {
                handler = new HttpClientHandler();
                if (handler.SupportsAutomaticDecompression)
                {
                    handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
                }

                retVal = new HttpClient(handler);
                retVal.DefaultRequestHeaders.UserAgent.ParseAdd("(Yort.Laybuy.InStore; en-nz) Yort.Laybuy.InStore/1.0");

                return(retVal);
            }
            catch
            {
                handler?.Dispose();
                retVal?.Dispose();

                throw;
            }
        }
Пример #5
0
        public void Dispose()
        {
            Disconnect();

            _client.Dispose();
            _clientHandler.Dispose();
        }
Пример #6
0
        /// <summary>
        /// Runs 'dotnet run' on the specified project while only exposing a HTTP endpoint.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="projectRelativeDirectoryPath">The project relative directory path.</param>
        /// <param name="action">The action to perform while the project is running.</param>
        /// <param name="noRestore">Whether to restore the project.</param>
        /// <param name="validateCertificate">Validate the project certificate.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns>A task representing the operation.</returns>
        public static async Task DotnetRun(
            this Project project,
            string projectRelativeDirectoryPath,
            Func <HttpClient, Task> action,
            bool?noRestore = true,
            Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> validateCertificate = null,
            TimeSpan?timeout = null)
        {
            var httpPort = PortHelper.GetFreeTcpPort();
            var httpUrl  = $"http://localhost:{httpPort}";

            var projectFilePath = Path.Combine(project.DirectoryPath, projectRelativeDirectoryPath);
            var dotnetRun       = await DotnetRunInternal(projectFilePath, noRestore, timeout, httpUrl);

            var httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false,
                ServerCertificateCustomValidationCallback = validateCertificate ?? DefaultValidateCertificate,
            };
            var httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(httpUrl)
            };

            try
            {
                await action(httpClient);
            }
            finally
            {
                httpClient.Dispose();
                httpClientHandler.Dispose();
                dotnetRun.Dispose();
            }
        }
Пример #7
0
        public async Task GetBidAndAskGold()
        {
            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };

            using (var client = new HttpClient(handler))
            {
                HttpResponseMessage response = await client.GetAsync("https://www.kitco.com/charts/livegold.html");

                var html = await response.Content.ReadAsStringAsync();

                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var bid      = htmlDoc.DocumentNode.Descendants("span").FirstOrDefault(node => node.GetAttributeValue("id", "").Equals("sp-bid"));
                var ask      = htmlDoc.DocumentNode.Descendants("span").FirstOrDefault(node => node.GetAttributeValue("id", "").Equals("sp-ask"));
                var bidValue = bid == null ? String.Empty : bid.FirstChild.InnerText;
                var askValue = ask == null ? String.Empty : ask.FirstChild.InnerText;
                ColorBuyGlobal = float.Parse(bidValue) >= float.Parse(BuyGlobal) ? upColor : downColor;
                BuyGlobal      = bidValue;

                ColorSellGlobal = float.Parse(askValue) >= float.Parse(BuyGlobal) ? upColor : downColor;
                SellGlobal      = askValue;

                RaisePropertyChanged("BuyGlobal");
                RaisePropertyChanged("ColorBuyGlobal");
                RaisePropertyChanged("SellGlobal");
                RaisePropertyChanged("ColorSellGlobal");
                handler.Dispose();
                client.Dispose();
            }
        }
Пример #8
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     _logger.LogInformation("Stopping");
     _httpClient.Dispose();
     _httpClientHandler.Dispose();
     return(Task.CompletedTask);
 }
Пример #9
0
        public async Task <List <UserDTO> > GetUsers()
        {
            var handler = new HttpClientHandler();

            handler.UseDefaultCredentials = true;
            var client = new HttpClient(handler);

            try
            {
                var response = await client.GetAsync("https://dl.dropboxusercontent.com/s/s8g63b149tnbg8x/users.json?dl=0");

                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();

                var settings = new JsonSerializerSettings();
                settings.DateFormatString = "HH':'mm' 'dd'.'MM'.'yy";
                var data = await Task.Run(() => JsonConvert.DeserializeObject <List <UserDTO> >(responseBody, settings));

                return(data);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            handler.Dispose();
            client.Dispose();
            return(new List <UserDTO>());
        }
Пример #10
0
        public bool StartUpload(string fileName, int assetId)
        {
            var handler = new HttpClientHandler()
            {
                UseDefaultCredentials = true
            };
            string     url    = "http://c0040597.itcs.hp.com:7860/Report/Upload";
            HttpClient client = new HttpClient(handler);

            MultipartFormDataContent form = new MultipartFormDataContent();

            form.Add(new StringContent(assetId.ToString()), "asset");
            byte[] fileContent = File.ReadAllBytes(fileName);

            form.Add(new ByteArrayContent(fileContent), "file", fileName);
            var task = client.PostAsync(url, form);

            task.Wait();
            var response = task.Result;

            client.Dispose();
            handler.Dispose();
            if (response.IsSuccessStatusCode)
            {
                return(true);
            }
            return(false);
        }
Пример #11
0
        private static HttpClient PrepareHTTPClient([NotNull] string authToken,
                                                    [CanBeNull][InstantHandle]
                                                    Action <HttpClientHandler> httpClientHandlerConfigurator)
        {
#pragma warning disable CA2000
            var handler = new HttpClientHandler(); // Disposal is performed by HttpClient
#pragma warning restore CA2000

            HttpClient httpClient;
            try
            {
                httpClientHandlerConfigurator?.Invoke(handler);
                httpClient = new HttpClient(handler, true);
            }
            catch
            {
                handler.Dispose();
                throw;
            }

            try
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Token {authToken}");
            }
            catch
            {
                httpClient.Dispose();
                throw;
            }

            return(httpClient);
        }
Пример #12
0
        protected override void Dispose(bool disposing)
        {
            HttpClientHandler?.Dispose();

            // base.Dispose will set the HttpClientHandler to null.
            base.Dispose(disposing);
        }
Пример #13
0
        protected async Task <T> _GetRaw <T>(string url) where T : JToken
        {
            if (null == _client)
            {
                var h = new HttpClientHandler()
                {
                    AllowAutoRedirect = false,
                    CookieContainer   = await GetCookieContainer(),
                    Credentials       = await GetCredentials()
                };
                var c = new HttpClient(h);
                AddAuthentication(c);
                if (null != Interlocked.CompareExchange(ref _client, c, null))
                {
                    c.Dispose();
                    h.Dispose();
                }
            }

            using (var s = await _client.GetStreamAsync(new Uri(Url, url).AbsoluteUri))
            {
                using (var tr = new StreamReader(s))
                {
                    using (var jr = new JsonTextReader(tr))
                    {
                        return((T)JToken.Load(jr));
                    }
                }
            }
        }
Пример #14
0
        protected async Task <T> _GetRaw <T>(string url) where T : JToken
        {
            if (null == _client)
            {
                var h = new HttpClientHandler()
                {
                    AllowAutoRedirect = false,
                    CookieContainer   = await GetCookieContainer(),
                    Credentials       = await GetCredentials()
                };
                var c = new HttpClient(h);
                AddAuthentication(c);
                if (null != Interlocked.CompareExchange(ref _client, c, null))
                {
                    c.Dispose();
                    h.Dispose();
                }
            }

            var sw = Stopwatch.StartNew();

            using (var res = await _client.GetAsync(new Uri(Url, url).AbsoluteUri))
            {
                RequestComplete(res, sw.Elapsed);
                res.EnsureSuccessStatusCode();
                using (var tr = new StreamReader(await res.Content.ReadAsStreamAsync()))
                {
                    using (var jr = new JsonTextReader(tr))
                    {
                        return((T)JToken.Load(jr));
                    }
                }
            }
        }
Пример #15
0
        void IDisposable.Dispose()
        {
            Debug.Assert(EventsToPublish.Any(), $"There are undelivered events on {PublisherName}");

            httpClient?.Dispose();
            httpClientHandler?.Dispose();
        }
Пример #16
0
 public void Dispose()
 {
     interactiveService.Dispose();
     httpClientHandler.Dispose();
     httpClient.Dispose();
     GC.SuppressFinalize(this);
 }
Пример #17
0
        public QRCodeResponse GetQRCode(string token, string format = "svg", int size = 300, int border = 0, bool transparent = true)
        {
            try
            {
                var requestData = new QRCodeData()
                {
                    token       = token,
                    format      = format,
                    size        = size,
                    border      = border,
                    transparent = transparent
                };

                HttpClientHandler handler = new HttpClientHandler();
                HttpClient        client  = new HttpClient(handler)
                {
                    BaseAddress = new Uri("https://mpc.getswish.net")
                };

                var httpRequestMessage = new HttpRequestMessage
                {
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri("https://mpc.getswish.net/qrg-swish/api/v1/commerce"),
                    Content    = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json")
                };

                var response = client.SendAsync(httpRequestMessage).Result;

                string errorMessage = string.Empty;
                string svgData      = string.Empty;

                if (response.IsSuccessStatusCode)
                {
                    var readAsStringAsync = response.Content.ReadAsStringAsync();
                    svgData = readAsStringAsync.Result;
                }
                else
                {
                    var readAsStringAsync = response.Content.ReadAsStringAsync();
                    errorMessage = readAsStringAsync.Result;
                }

                client.Dispose();
                handler.Dispose();

                return(new QRCodeResponse()
                {
                    Error = errorMessage,
                    SVGData = svgData
                });
            }
            catch (Exception ex)
            {
                return(new QRCodeResponse()
                {
                    Error = ex.ToString(),
                    SVGData = string.Empty
                });
            }
        }
Пример #18
0
    // <Snippet1>
    static async Task Main()
    {
        // Create an HttpClientHandler object and set to use default credentials
        HttpClientHandler handler = new HttpClientHandler();

        // Set custom server validation callback
        handler.ServerCertificateCustomValidationCallback = ServerCertificateCustomValidation;

        // Create an HttpClient object
        HttpClient client = new HttpClient(handler);

        // Call asynchronous network methods in a try/catch block to handle exceptions
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://docs.microsoft.com/");

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Read {responseBody.Length} characters");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine($"Message: {e.Message} ");
        }

        // Need to call dispose on the HttpClient and HttpClientHandler objects
        // when done using them, so the app doesn't leak resources
        handler.Dispose();
        client.Dispose();
    }
Пример #19
0
        private void ResetHandler()
        {
            if (requestHandler != null)
            {
                requestHandler.Dispose();
            }

            requestHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                AllowAutoRedirect      = false,
                UseDefaultCredentials  = false,
                UseCookies             = false
            };

            if (httpClient != null)
            {
                httpClient.Dispose();
            }

            httpClient = new HttpClient(requestHandler)
            {
                MaxResponseContentBufferSize = configuration.MaxResponseContentBufferSize,
                Timeout = TimeSpan.FromSeconds(configuration.RequestTimeout)
            };

            SetHttpRequestHeader("User-Agent", CheckoutConfiguration.ClientUserAgentName);
            httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("Gzip"));
        }
Пример #20
0
// <Snippet1>
    static async Task Main()
    {
        // Create an HttpClientHandler object and set to use default credentials
        HttpClientHandler handler = new HttpClientHandler();

        handler.UseDefaultCredentials = true;

        // Create an HttpClient object
        HttpClient client = new HttpClient(handler);

        // Call asynchronous network methods in a try/catch block to handle exceptions
        try
        {
            HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }

        // Need to call dispose on the HttpClient and HttpClientHandler objects
        // when done using them, so the app doesn't leak resources
        handler.Dispose(true);
        client.Dispose(true);
    }
Пример #21
0
        public async Task ChangeProxy1()
        {
            var newProxy = WebRequest.DefaultWebProxy;

            try
            {
                handler1.Proxy = newProxy;
            }
            catch (InvalidOperationException)
            {
                var cookieContainer = handler1.CookieContainer;
                var timeout         = client1.Timeout;

                client1.Dispose();
                handler1.Dispose();

                handler1 = new HttpClientHandler()
                {
                    UseCookies        = true,
                    AllowAutoRedirect = false,
                    Proxy             = newProxy,
                    CookieContainer   = cookieContainer
                };

                client1 = new HttpClient(handler1)
                {
                    Timeout = timeout
                };
            }

            _ = await client1.GetStringAsync("https://api.ipify.org/");
        }
Пример #22
0
        public void Dispose()
        {
            // try cancel pending requests
            try
            {
                client.CancelPendingRequests();
            }
            catch { }

            // try dispose
            try
            {
                client.Dispose();
            }
            catch { }

            client = null;

            try
            {
                handler.Dispose();
            }
            catch { }

            handler = null;

            // remove from service
            service.SessionClosed(this);
        }
Пример #23
0
        public void Dispose()
        {
            if (!_isDisposed)
            {
                if (_httpClientObj != null)
                {
                    _httpClientObj.Dispose();
                    _httpClientObj = null;
                }

                // HttpClientHandler that is used to create HttpClient will automatically be disposed when HttpClient is disposed
                // But in case the client handler didn't end up being used by the HttpClient, we explicitly dispose it here.
                if (_httpClientHandler != null)
                {
                    _httpClientHandler?.Dispose();
                    _httpClientHandler = null;
                }

                // The associated TokenRefresher should be disposed by the http client helper only when the http client
                // is the primary transport handler.
                // For eg. we create HttpTransportHandler instances for file upload operations even though the client might be
                // initialized via MQTT/ AMQP. In those scenarios, since the shared TokenRefresher resource would be primarily used by the
                // corresponding transport layers (MQTT/ AMQP), the diposal should be delegated to them and it should not be disposed here.
                // The only scenario where the TokenRefresher should be disposed here is when the client has been initialized using HTTP.
                if (_isClientPrimaryTransportHandler &&
                    _authenticationHeaderProvider is IotHubConnectionString iotHubConnectionString &&
                    iotHubConnectionString.TokenRefresher != null &&
                    iotHubConnectionString.TokenRefresher.DisposalWithClient)
                {
                    iotHubConnectionString.TokenRefresher.Dispose();
                }

                _isDisposed = true;
            }
        }
Пример #24
0
        public void CreateHttpClient()
        {
            try
            {
                APIBaseAddress = new Uri(APIBaseURL);
                // dispose old connection
                if (httpClient != null)
                {
                    httpClient.Dispose();
                }
                if (handler != null)
                {
                    handler.Dispose();
                }

                handler         = new HttpClientHandler();
                this.httpClient = new HttpClient(handler, false)
                {
                    BaseAddress = APIBaseAddress
                };

                this.httpClient.Timeout = WebRequestTimeout;
                this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(DataFormat));
            }
            catch (Exception)
            {
                this.httpClient = null;
            }
        }
Пример #25
0
 public void Dispose()
 {
     handler.Dispose();
     client.Dispose();
     content.Dispose();
     response.Dispose();
 }
        private HttpClient InitializeHttpClient(TimeSpan timeout)
        {
            HttpClient httpClient;
            var        httpHandler = new HttpClientHandler();

            try
            {
                httpHandler.AllowAutoRedirect = false;
                //httpHandler.MaxRequestContentBufferSize = 1024;
                httpHandler.UseCookies            = false;
                httpHandler.UseDefaultCredentials = false;

                httpClient = new HttpClient(httpHandler, true);
            }
            catch
            {
                httpHandler.Dispose();
                throw;
            }

            httpClient.DefaultRequestHeaders.ExpectContinue = false;
            httpClient.DefaultRequestHeaders.UserAgent.Clear();
            httpClient.DefaultRequestHeaders.UserAgent.Add(GetUserAgent());
            httpClient.Timeout = timeout;
            httpClient.MaxResponseContentBufferSize = 1024;
            return(httpClient);
        }
Пример #27
0
        public void Dispose()
        {
            _httpClientWithDefaultTimeout.Dispose();
            _httpClientWithNoTimeout.Dispose();

            // Since HttpClientHandler was passed to the 2 HttpClients above, but told them not to dispose it, we want to dispose this after
            _httpClientHandler.Dispose();
        }
Пример #28
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _client.Dispose();
         _handler.Dispose();
     }
 }
Пример #29
0
 public void Dispose()
 {
     if (defaultHttpClientHandler != null)
     {
         defaultHttpClientHandler.Dispose();
         defaultHttpClientHandler = null;
     }
 }
Пример #30
0
 public void Dispose()
 {
     try
     {
         httpClient?.Dispose();
         httpClientHandler?.Dispose();
     }
     catch { }
 }