FLURL: HTTP POST request in C#
using Flurl;
using Flurl.Http;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
try
{
string apiUrl = "https://jsonplaceholder.typicode.com/posts"; // Replace with your API endpoint
var postContent = new
{
userId = 1,
id = 101, // Replace with the desired ID
title = "Flurl POST Example",
body = "This is a simple example of making a POST request using Flurl."
};
// Make a POST request using Flurl
var response = await apiUrl
.WithHeader("Content-Type", "application/json") // Optional: Set the request header
.PostJsonAsync(postContent);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("POST request successful. Response:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"POST request failed with status code: {response.StatusCode}");
}
}
catch (FlurlHttpTimeoutException ex)
{
Console.WriteLine($"Timeout error: {ex.Message}");
}
catch (FlurlHttpException ex)
{
Console.WriteLine($"HTTP error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
In this example, we use Flurl to make a POST request to the "https://jsonplaceholder.typicode.com/posts" endpoint (you can replace this URL with your own API endpoint). We provide JSON data in the postContent object, set the "Content-Type" header to "application/json," and use the PostJsonAsync method to send the POST request. We then handle the response, checking for success and printing the response content or any error messages.