PostAsync
PostAsync у
HttpClient
передаёт HttpContent. Заглушка
запоминает request.Method
и отвечает 200 без сети.
Синтаксис
HttpResponseMessage response = await client.PostAsync(
"http://abcde.example/", content);
Пример
Давайте проверить метод запроса:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
public static string LastMethod;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
LastMethod = request.Method.Method;
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Program
{
static async Task Main()
{
using HttpClient client = new HttpClient(new Stub());
HttpContent body = new StringContent("abcde");
await client.PostAsync("http://abcde.example/", body);
string res = Stub.LastMethod;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"POST"
Пример
Давайте прочитать код ответа:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Program
{
static async Task Main()
{
using HttpClient client = new HttpClient(new Stub());
HttpContent body = new StringContent("abcde");
HttpResponseMessage response = await client.PostAsync(
"http://abcde.example/", body);
int res = (int)response.StatusCode;
Console.WriteLine(res);
}
}
Результат выполнения кода:
200
Пример
Давайте прочитать тело ответа:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Program
{
static async Task Main()
{
using HttpClient client = new HttpClient(new Stub());
HttpContent body = new StringContent("abcde");
HttpResponseMessage response = await client.PostAsync(
"http://abcde.example/", body);
string res = await response.Content.ReadAsStringAsync();
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
PutAsync,
запрос PUT -
DeleteAsync,
запрос DELETE -
SendAsync,
произвольный запрос -
GetAsync,
запрос GET