c# sample HttpClient POST request code example

Example 1: example HttpClient c# Post

//Base code from: http://zetcode.com/csharp/httpclient/
public async string Example() 
{
  	//The data that needs to be sent. Any object works.
	var pocoObject = new 
	{
	  	Name = "John Doe",
		Occupation = "gardener"
	};

  	//Converting the object to a json string. NOTE: Make sure the object doesn't contain circular references.
	string json = JsonConvert.SerializeObject(pocoObject);
  	
  	//Needed to setup the body of the request
	StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

  	//The url to post to.
	var url = "https://httpbin.org/post";
	var client = new HttpClient();

  	//Pass in the full URL and the json string content
	var response = await client.PostAsync(url, data);

  	//It would be better to make sure this request actually made it through
	string result = await response.Content.ReadAsStringAsync();
  	
  	//close out the client
  	client.Dispose();
  
	return result;
}

Example 2: C# HttpClient POST request

using System;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace HttpClientPost
{
    class Person
    {
        public string Name { get; set; }
        public string Occupation { get; set; }

        public override string ToString()
        {
            return $"{Name}: {Occupation}";
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var person = new Person();
            person.Name = "John Doe";
            person.Occupation = "gardener";

            var json = JsonConvert.SerializeObject(person);
            var data = new StringContent(json, Encoding.UTF8, "application/json");

            var url = "https://httpbin.org/post";
            using var client = new HttpClient();

            var response = await client.PostAsync(url, data);

            string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(result);
        }
    }
}