本文整理汇总了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);
}
}
}
}
示例2: ConnectTimeout_InvalidValues
public void ConnectTimeout_InvalidValues(long ms)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms));
}
}
示例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);
}
}
示例4: InvalidValue_ThrowsException
public void InvalidValue_ThrowsException(int invalidValue)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
}
}
示例5: Default_Get_Null
public void Default_Get_Null()
{
using (var handler = new HttpClientHandler())
{
Assert.Null(handler.DefaultProxyCredentials);
}
}
示例6: ClientCertificateOptions_InvalidArg_ThrowsException
public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
}
}
示例7: Default_ExpectedValue
public void Default_ExpectedValue()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
}
}
示例8: Set_InvalidValues_Throws
public void Set_InvalidValues_Throws(int invalidValue)
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxConnectionsPerServer = invalidValue);
}
}
示例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);
}
}
示例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.");
}
}
}
示例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);
}
}
示例12: Default_MaxResponseHeadersLength
public void Default_MaxResponseHeadersLength()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength);
}
}
示例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);
}
示例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);
}
}
示例15: DefaultProtocols_MatchesExpected
public void DefaultProtocols_MatchesExpected()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}