make a http request with a custom body as form url encoded in csharp

Here's an example of how to make an HTTP POST request with a custom body as form-urlencoded in C# using the HttpWebRequest class:

main.cs
string url = "https://example.com/api";
string formData = "name=value&foo=bar"; // Your form data in key-value pairs

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

using (Stream stream = request.GetRequestStream())
{
    byte[] byteArray = Encoding.UTF8.GetBytes(formData);
    stream.Write(byteArray, 0, byteArray.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
        string responseBody = reader.ReadToEnd();
        Console.WriteLine(responseBody);
    }
}
797 chars
24 lines

In this example, we set the url variable to the API endpoint that we want to send our HTTP request to. We then create a HttpWebRequest object and set its properties: Method to POST, ContentType to application/x-www-form-urlencoded, and the ContentLength to the length of our formData string.

Next, we get the request stream, convert our formData to a byte array, and write it to the request stream.

We then send the HTTP POST request to the API endpoint, wait for the response, and get the response body using a StreamReader. Finally, we print the response body to the console.

gistlibby LogSnag