make a http request with a custom body as text in csharp

To make an HTTP request with a custom body as text in C#, you can use the HttpClient class which is a part of the System.Net.Http namespace.

Here is an example code snippet that sends a POST request with a custom text body to a server -

main.cs
using System.Net.Http;
using System.Text;

class Program
{
    static async void MakeRequest()
    {
        using var httpClient = new HttpClient();
        var requestUrl = "http://example.com/api/resource";

        // define the request body as text
        var requestBody = "This is the request body";

        var requestContent = new StringContent(requestBody, Encoding.UTF8, "text/plain");

        // send the HTTP POST request
        var response = await httpClient.PostAsync(requestUrl, requestContent);

        // read the response
        var responseBody = await response.Content.ReadAsStringAsync();

        // print the response body
        Console.WriteLine(responseBody);
    }

    static void Main(string[] args)
    {
        MakeRequest();
        Console.ReadKey();
    }
}
802 chars
32 lines

In the above code, we are creating an instance of the HttpClient class and using it to send a POST request to a server with a custom text body. We are defining the request body as a string and wrapping it in a StringContent object with the specified encoding and media type. Finally, we are printing the response body received from the server.

related categories

gistlibby LogSnag