Sending a POST request with a string payload using System.Net.HttpClient
suggest changeOn .NET Framework 4.5 and later, HttpClient is in the System.Net.Http assembly. The Microsoft HTTP Client Libraries NuGet package backports it to .NET Framework 4.0. Calling .Result blocks, and on a UI or ASP.NET request thread it can deadlock. Prefer await inside an async method.
string requestUri = "http://www.example.com";
string requestBodyString = "Request body string.";
string contentType = "text/plain";
string requestMethod = "POST";
using (var client = new HttpClient())
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(requestUri),
Method = new HttpMethod(requestMethod),
};
byte[] requestBodyBytes = Encoding.UTF8.GetBytes(requestBodyString);
request.Content = new ByteArrayContent(requestBodyBytes);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
HttpResponseMessage result = client.SendAsync(request).Result;
result.EnsureSuccessStatusCode();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents