Using the HttpClient class from the System.Net.Http namespace
xxxxxxxxxx
using System.Net.Http;
using System.Text;
public async void PostRequest(string url, string data)
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
the PostRequest method takes two parameters: the url where the request will be sent, and the data to be sent as the body of the request. The data is passed as a string, but you can change the content type and encoding as needed.
The HttpClient class is created inside a using block to ensure that it is properly disposed of after use. The StringContent class is used to create the request body, specifying the content type and encoding. The PostAsync method is called on the HttpClient object, passing in the url and content. Finally, the response is read as a string and printed to the console.
xxxxxxxxxx
using System.Net.Http;
HttpClient client = new HttpClient();
/// POST ///
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
/// GET ///
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
xxxxxxxxxx
using System.Net.Http;
private static readonly HttpClient client = new();
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(
"http://www.example.com/postable.aspx", content);
var result = await response.Content.ReadAsStringAsync();