本文整理汇总了C#中HttpClient.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.SendAsync方法的具体用法?C# HttpClient.SendAsync怎么用?C# HttpClient.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpClient
的用法示例。
在下文中一共展示了HttpClient.SendAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendRequestAndGetResponseVersionAsync
private async Task<Version> SendRequestAndGetResponseVersionAsync(Version requestVersion, Uri server)
{
var request = new HttpRequestMessage(HttpMethod.Get, server);
if (requestVersion != null)
{
request.Version = requestVersion;
}
else
{
// The default value for HttpRequestMessage.Version is Version(1,1).
// So, we need to set something different to test the "unknown" version.
request.Version = new Version(0,0);
}
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return response.Version;
}
}
示例2: SendAsync_RequestVersion20_ResponseVersion20
public async Task SendAsync_RequestVersion20_ResponseVersion20(Uri server)
{
_output.WriteLine(server.AbsoluteUri.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(new Version(2, 0), response.Version);
}
}
}
示例3: SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported
public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server)
{
// We don't currently have a good way to test whether HTTP/2 is supported without
// using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses.
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler, false))
{
// It is generally expected that the test hosts will be trusted, so we don't register a validation
// callback in the usual case.
//
// However, on our Debian 8 test machines, a combination of a server side TLS chain,
// the client chain processor, and the distribution's CA bundle results in an incomplete/untrusted
// certificate chain. See https://github.com/dotnet/corefx/issues/9244 for more details.
if (PlatformDetection.IsDebian8)
{
// Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
{
Assert.InRange(chain.ChainStatus.Length, 0, 1);
if (chain.ChainStatus.Length > 0)
{
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.ChainStatus[0].Status);
}
return true;
};
}
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(
response.Version == new Version(2, 0) ||
response.Version == new Version(1, 1),
"Response version " + response.Version);
}
}
}
示例4: SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent
public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer)
{
Content = new StringContent(ExpectedContent)
};
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE")
{
// [ActiveIssue(9023, PlatformID.Windows)]
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
else
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.False(responseContent.Contains(ExpectedContent));
}
}
}
}
示例5: SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer);
request.Content = new StringContent(ExpectedContent);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
ExpectedContent);
}
}
}
示例6: SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
}
}
}
示例7: SendGraphGetRequest
public static async Task<string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret)
{
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret);
// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
// AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so.
//var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));
//// We don't care which policy is used to access the TaskService, so let's use the most recent policy
//var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value;
//var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy);
//// First, use ADAL to acquire a token using the app's identity (the credential)
//// The first parameter is the resource we want an access_token for; in this case, the Graph API.
var result = authContext.AcquireToken("https://graph.windows.net", credential);
// For B2C user managment, be sure to use the beta Graph API version.
var http = new HttpClient();
var url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta";
if (!string.IsNullOrEmpty(query))
{
url += "&" + query;
}
//Console.ForegroundColor = ConsoleColor.Cyan;
//Console.WriteLine("GET " + url);
//Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
//Console.WriteLine("");
// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
var request = new HttpRequestMessage(HttpMethod.Get, url);
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
var response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
object formatted = JsonConvert.DeserializeObject(error);
throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
//Console.ForegroundColor = ConsoleColor.Green;
//Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
//Console.WriteLine("");
return await response.Content.ReadAsStringAsync();
}
示例8: SendAsync_Cancel_CancellationTokenPropagates
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer);
TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, cts.Token));
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
}
}
示例9: PostUsingAuthHelper
private async Task PostUsingAuthHelper(
Uri serverUri,
string requestBody,
HttpContent requestContent,
NetworkCredential credential,
bool preAuthenticate)
{
var handler = new HttpClientHandler();
handler.PreAuthenticate = preAuthenticate;
handler.Credentials = credential;
using (var client = new HttpClient(handler))
{
// Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming
// that the authentication will be cached and re-used later when PreAuthenticate is true.
var request = new HttpRequestMessage(HttpMethod.Head, serverUri);
HttpResponseMessage response;
using (response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Now send POST request.
request = new HttpRequestMessage(HttpMethod.Post, serverUri);
request.Content = requestContent;
requestContent.Headers.ContentLength = null;
request.Headers.TransferEncodingChunked = true;
using (response = await client.PostAsync(serverUri, requestContent))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
true,
requestBody);
}
}
}
示例10: SendAsync_ReadFromSlowStreamingServer_PartialDataReturned
public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned()
{
// TODO: This is a placeholder until GitHub Issue #2383 gets resolved.
const string SlowStreamingServer = "http://httpbin.org/drip?numbytes=8192&duration=15&delay=1&code=200";
int bytesRead;
byte[] buffer = new byte[8192];
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, SlowStreamingServer);
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Stream stream = await response.Content.ReadAsStreamAsync();
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
}
_output.WriteLine("Bytes read from stream: {0}", bytesRead);
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
}
示例11: SendRequestAndGetRequestVersionAsync
private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion)
{
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = requestVersion;
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
string statusLine = reader.ReadLine();
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = new Version(1, 0);
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = new Version(1, 1);
}
else
{
Assert.True(false, "Invalid HTTP request version");
}
await writer.WriteAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n");
s.Shutdown(SocketShutdown.Send);
});
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
return receivedRequestVersion;
}
示例12: StartAsync
private static async Task<ProxyResult> StartAsync(TcpListener listener, bool requireAuth, bool expectCreds)
{
ProxyResult result = new ProxyResult();
var headers = new Dictionary<string, string>();
Socket clientSocket = null;
Stream clientStream = null;
StreamReader clientReader = null;
string url = null;
try
{
// Get and parse the incoming request.
Func<Task> getAndReadRequest = async () => {
clientSocket = await listener.AcceptSocketAsync().ConfigureAwait(false);
clientStream = new NetworkStream(clientSocket, ownsSocket: false);
clientReader = new StreamReader(clientStream, Encoding.ASCII);
headers.Clear();
url = clientReader.ReadLine().Split(' ')[1];
string line;
while (!string.IsNullOrEmpty(line = clientReader.ReadLine()))
{
string[] headerParts = line.Split(':');
headers.Add(headerParts[0].Trim(), headerParts[1].Trim());
}
};
await getAndReadRequest().ConfigureAwait(false);
// If we're expecting credentials, look for them, and if we didn't get them, send back
// a 407 response. Optionally, process a new request that would expect credentials.
if (requireAuth && !headers.ContainsKey("Proxy-Authorization"))
{
// Send back a 407
await clientSocket.SendAsync(
new ArraySegment<byte>(Encoding.ASCII.GetBytes("HTTP/1.1 407 Proxy Auth Required\r\nProxy-Authenticate: Basic\r\n\r\n")),
SocketFlags.None).ConfigureAwait(false);
clientSocket.Shutdown(SocketShutdown.Send);
clientSocket.Dispose();
if (expectCreds)
{
// Wait for a new connection that should have an auth header this time and parse it.
await getAndReadRequest().ConfigureAwait(false);
}
else
{
// No credentials will be coming in a subsequent request.
return default(ProxyResult);
}
}
// Store any auth header we may have for later comparison.
string authValue;
if (headers.TryGetValue("Proxy-Authorization", out authValue))
{
result.AuthenticationHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Substring("Basic ".Length)));
}
// Forward the request to the server.
var request = new HttpRequestMessage(HttpMethod.Get, url);
foreach (var header in headers) request.Headers.Add(header.Key, header.Value);
using (HttpClient outboundClient = new HttpClient())
using (HttpResponseMessage response = await outboundClient.SendAsync(request).ConfigureAwait(false))
{
// Transfer the response headers from the server to the client.
var sb = new StringBuilder($"HTTP/{response.Version.ToString(2)} {(int)response.StatusCode} {response.ReasonPhrase}\r\n");
foreach (var header in response.Headers.Concat(response.Content.Headers))
{
sb.Append($"{header.Key}: {string.Join(", ", header.Value)}\r\n");
}
sb.Append("\r\n");
byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
await clientStream.WriteAsync(headerBytes, 0, headerBytes.Length).ConfigureAwait(false);
// Forward the content from the server, both to the client and to a memory stream which we'll use
// to return the data from the proxy.
var resultBody = new MemoryStream();
using (Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
byte[] buffer = new byte[0x1000];
int bytesRead = 0;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
await clientStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
resultBody.Write(buffer, 0, bytesRead);
}
}
// Return the result
result.ResponseContent = resultBody.ToArray();
return result;
}
}
finally
{
clientSocket.Dispose();
listener.Stop();
}
}
示例13: SendHttpWebRequest
/// <summary>
/// Sends an HTTP request to the given URL, and receives the response.
/// Note: This does not do a check to see if the currently stored creds are valid.
/// </summary>
/// <param name="url">The destination URL.</param>
/// <param name="method">The desired HTTP Request Method.</param>
/// <param name="data">The data to include in the message body.</param>
/// <param name="contentType">The Content-Type of the request. Default value is "application/json"</param>
/// <param name="timeout">How long to wait for the request to complete. Default wait time is 3 seconds.</param>
/// <returns>Returns the response text on success. Throws a WebException on failure.</returns>
private string SendHttpWebRequest(string url, HttpMethod method, string data, string contentType = "application/json", int timeout = 3000)
{
try
{
// CREATE REQUEST
using (HttpClient httpClient = new HttpClient())
{
HttpRequestMessage msg = new HttpRequestMessage(method, new Uri(url));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
if (data != null)
{
msg.Content = new StringContent(data, Encoding.ASCII, contentType);
}
else if (!method.Equals(HttpMethod.Get))
{
msg.Content = new StringContent("", Encoding.ASCII, contentType);
}
// TODO: Does this work when creds are null?
// answer: no
//if (this.isAuthroized)
//{
// httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("oy5ct3rjz7dob56syzaa65npbpumuvjm6d26fzdlupvighy2c4kq")));//":6cc3meg6fhnkbz22qocgetkndxrfjca76emcnanjodgiooir3xoq")));
//}
// GET RESPONSE
HttpResponseMessage resp = httpClient.SendAsync(msg).Result;
if (!resp.IsSuccessStatusCode)
{
throw new WebException("Error contacting serer. " + resp.ReasonPhrase);
}
return resp.Content.ReadAsStringAsync().Result;
}
}
catch (System.Net.WebException e)
{
this.LogTextBox.Text += "\r\n" + e.Message;
return null;
}
}
示例14: SendRequestAndGetRequestVersionAsync
private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion)
{
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = requestVersion;
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
List<string> receivedRequest = await LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
string statusLine = receivedRequest[0];
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = new Version(1, 0);
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = new Version(1, 1);
}
else
{
Assert.True(false, "Invalid HTTP request version");
}
}
});
return receivedRequestVersion;
}
示例15: PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered
public async Task PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered()
{
using (var client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
bool contentDisposed = false;
Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new DelegateContent
{
SerializeToStreamAsyncDelegate = (contentStream, contentTransport) => contentStream.WriteAsync(new byte[100], 0, 100),
TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100),
DisposeDelegate = _ => contentDisposed = true
}
}, HttpCompletionOption.ResponseContentRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
// Read headers from client
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
// Send back all headers and some but not all of the response
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n");
await writer.WriteAsync("abcd"); // less than contentLength
// The request content should not be disposed of until all of the response has been sent
await Task.Delay(1); // a little time to let data propagate
Assert.False(contentDisposed, "Expected request content not to be disposed");
// Send remaining response content
await writer.WriteAsync("efghij");
s.Shutdown(SocketShutdown.Send);
// The task should complete and the request content should be disposed
using (HttpResponseMessage response = await post)
{
Assert.True(contentDisposed, "Expected request content to be disposed");
Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync());
}
return null;
});
});
}
}