make a http request with a custom body as form data in csharp

To make an HTTP request with a custom body as form data in C#, you can use the HttpClient class and the FormUrlEncodedContent class. Here's an example:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var body = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("key1", "value1"),
            new KeyValuePair<string, string>("key2", "value2")
        });
        var response = await client.PostAsync("https://example.com/api", body);
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}
571 chars
20 lines

In this example, we first create an instance of the HttpClient class. We then create an instance of the FormUrlEncodedContent class, passing in an array of key-value pairs representing the form data we want to send. We then call the PostAsync method on the HttpClient instance, passing in the URL we want to send the request to and the form data as the request body. Finally, we read the response body as a string and print it to the console.

related categories

gistlibby LogSnag