Sending a POST request with a string payload using System.Net.HttpClient

suggest change

On .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();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents