send http post in csharp

To send an HTTP POST request in C#, you can use the HttpClient class in the System.Net.Http namespace. Here's an example:

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

public static async Task<string> SendPostRequest(string url, string data)
{
    using (var client = new HttpClient())
    {
        var content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);
        return await response.Content.ReadAsStringAsync();
    }
}
414 chars
14 lines

This method takes two parameters: the URL to which you want to send the HTTP POST request, and the data you want to include in the request body. The data parameter must be formatted as a JSON string in this example, but you can also use different formats like XML or plain text.

The method creates a HttpClient instance and uses it to send the HTTP POST request with the PostAsync method. The request body is included in the request as a StringContent instance with the media type application/json.

The method then reads the response body as a string with the ReadAsStringAsync method on the HttpContent returned by response.Content.

You can call this method like this:

main.cs
string url = "https://www.example.com/api/users";
string data = "{ \"name\": \"John Doe\", \"email\": \"john.doe@example.com\" }";
string response = await SendPostRequest(url, data);
Console.WriteLine(response);
212 chars
5 lines

This sends an HTTP POST request to https://www.example.com/api/users with the body { "name": "John Doe", "email": "john.doe@example.com" }, and prints the response body to the console.

gistlibby LogSnag