make a http post request in csharp

Here's an example of making an HTTP POST request in C# using HttpWebRequest:

main.cs
string url = "https://example.com/api/users";
string data = "name=John&email=john@example.com";

byte[] bytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader reader = new StreamReader(responseStream))
        {
            string responseText = reader.ReadToEnd();
            Console.WriteLine(responseText);
        }
    }
}
788 chars
27 lines

In this example, we first define the URL we want to make the HTTP POST request to and the data we want to send along with the request. We then convert the data to a byte array and set various properties on the HttpWebRequest object, including the HTTP method (POST), content type (application/x-www-form-urlencoded), and content length. We then obtain a Stream object from the HttpWebRequest object's GetRequestStream() method, write the data to it, and close the stream. Finally, we obtain a HttpWebResponse object from the request's GetResponse() method, and read the response text from its StreamReader. Note that we encapsulate the HttpWebResponse and StreamReader objects in using statements to ensure that they are cleaned up properly.

gistlibby LogSnag