当前位置: 首页>>代码示例>>C#>>正文


C# HttpClientHandler类代码示例

本文整理汇总了C#中HttpClientHandler的典型用法代码示例。如果您正苦于以下问题:C# HttpClientHandler类的具体用法?C# HttpClientHandler怎么用?C# HttpClientHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpClientHandler类属于命名空间,在下文中一共展示了HttpClientHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ThresholdExceeded_ThrowsException

        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                s.Listen(1);
                var ep = (IPEndPoint)s.LocalEndPoint;

                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead);

                    using (Socket server = s.Accept())
                    using (Stream serverStream = new NetworkStream(server, ownsSocket: false))
                    using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                        byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                        serverStream.Write(headerData, 0, headerData.Length);
                    }

                    if (shouldSucceed)
                    {
                        (await getAsync).Dispose();
                    }
                    else
                    {
                        await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                    }
                }
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:35,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例2: ConnectTimeout_InvalidValues

 public void ConnectTimeout_InvalidValues(long ms)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms));
     }
 }
开发者ID:tstringer,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.Timeouts.cs

示例3: DisabledProtocols_SetSslProtocols_ThrowsException

#pragma warning restore 0618
        public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
        {
            using (var handler = new HttpClientHandler())
            {
                Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
            }
        }
开发者ID:alessandromontividiu03,项目名称:corefx,代码行数:8,代码来源:HttpClientHandlerTest.SslProtocols.cs

示例4: InvalidValue_ThrowsException

 public void InvalidValue_ThrowsException(int invalidValue)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
     }
 }
开发者ID:swaroop-sridhar,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例5: Default_Get_Null

 public void Default_Get_Null()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Null(handler.DefaultProxyCredentials);
     }
 }
开发者ID:naamunds,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.DefaultProxyCredentials.cs

示例6: ClientCertificateOptions_InvalidArg_ThrowsException

 public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
     }
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.ClientCertificates.cs

示例7: Default_ExpectedValue

 public void Default_ExpectedValue()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
     }
 }
开发者ID:SGuyGe,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.MaxConnectionsPerServer.cs

示例8: Set_InvalidValues_Throws

 public void Set_InvalidValues_Throws(int invalidValue)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxConnectionsPerServer = invalidValue);
     }
 }
开发者ID:SGuyGe,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.MaxConnectionsPerServer.cs

示例9: Ctor_ExpectedDefaultPropertyValues

 public void Ctor_ExpectedDefaultPropertyValues()
 {
     using (var handler = new HttpClientHandler())
     {
         // Same as .NET Framework (Desktop).
         Assert.True(handler.AllowAutoRedirect);
         Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
         CookieContainer cookies = handler.CookieContainer;
         Assert.NotNull(cookies);
         Assert.Equal(0, cookies.Count);
         Assert.Null(handler.Credentials);
         Assert.Equal(50, handler.MaxAutomaticRedirections);
         Assert.False(handler.PreAuthenticate);
         Assert.Equal(null, handler.Proxy);
         Assert.True(handler.SupportsAutomaticDecompression);
         Assert.True(handler.SupportsProxy);
         Assert.True(handler.SupportsRedirectConfiguration);
         Assert.True(handler.UseCookies);
         Assert.False(handler.UseDefaultCredentials);
         Assert.True(handler.UseProxy);
         
         // Changes from .NET Framework (Desktop).
         Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
         Assert.Equal(0, handler.MaxRequestContentBufferSize);
     }
 }
开发者ID:nbilling,项目名称:corefx,代码行数:26,代码来源:HttpClientHandlerTest.cs

示例10: HttpClient_ClientUsesAuxRecord_Ok

        public async Task HttpClient_ClientUsesAuxRecord_Ok()
        {
            X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate();

            var server = new SchSendAuxRecordTestServer(serverCert);
            int port = server.StartServer();

            string requestString = "https://localhost:" + port.ToString();
            
            using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
            using (var client = new HttpClient(handler))
            {
                var tasks = new Task[2];
                tasks[0] = server.RunTest();
                tasks[1] = client.GetStringAsync(requestString);
            
                await Task.WhenAll(tasks).TimeoutAfter(15 * 1000);
            
                if (server.IsInconclusive)
                {
                    _output.WriteLine("Test inconclusive: The Operating system preferred a non-CBC or Null cipher.");
                }
                else
                {
                    Assert.True(server.AuxRecordDetected, "Server reports: Client auxiliary record not detected.");
                }
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:28,代码来源:SchSendAuxRecordHttpTest.cs

示例11: UseCallback_ValidCertificate_ExpectedValuesDuringCallback

        public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
        {
            var handler = new HttpClientHandler();
            using (var client = new HttpClient(handler))
            {
                bool callbackCalled = false;
                handler.CheckCertificateRevocationList = checkRevocation;
                handler.ServerCertificateValidationCallback = (request, cert, chain, errors) => {
                    callbackCalled = true;
                    Assert.NotNull(request);
                    Assert.Equal(SslPolicyErrors.None, errors);
                    Assert.True(chain.ChainElements.Count > 0);
                    Assert.NotEmpty(cert.Subject);
                    Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
                    return true;
                };

                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }

                Assert.True(callbackCalled);
            }
        }
开发者ID:eerhardt,项目名称:corefx,代码行数:25,代码来源:HttpClientHandlerTest.ServerCertificates.cs

示例12: Default_MaxResponseHeadersLength

 public void Default_MaxResponseHeadersLength()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength);
     }
 }
开发者ID:swaroop-sridhar,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例13: ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed

        [PlatformSpecific(PlatformID.AnyUnix)] // proxies set via the http_proxy environment variable are specific to Unix
        public void ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);

            const string ExpectedUsername = "rightusername";
            const string ExpectedPassword = "rightpassword";

            // libcurl will read a default proxy from the http_proxy environment variable.  Ensure that when it does,
            // our default proxy credentials are used.  To avoid messing up anything else in this process, we run the
            // test in another process.
            var psi = new ProcessStartInfo();
            psi.Environment.Add("http_proxy", $"http://localhost:{port}");
            RemoteInvoke(() =>
            {
                using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                    var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword);
                    handler.DefaultProxyCredentials = creds;

                    Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                    Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                }
                return SuccessExitCode;
            }, new RemoteInvokeOptions { StartInfo = psi }).Dispose();

            Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
        }
开发者ID:SamuelEnglard,项目名称:corefx,代码行数:33,代码来源:HttpClientHandlerTest.DefaultProxyCredentials.cs

示例14: ProxyExplicitlyProvided_DefaultCredentials_Ignored

        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
开发者ID:naamunds,项目名称:corefx,代码行数:26,代码来源:HttpClientHandlerTest.DefaultProxyCredentials.cs

示例15: DefaultProtocols_MatchesExpected

 public void DefaultProtocols_MatchesExpected()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(SslProtocols.None, handler.SslProtocols);
     }
 }
开发者ID:alessandromontividiu03,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.SslProtocols.cs


注:本文中的HttpClientHandler类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。