c# post request code example

Example 1: c# post get request

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");

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);
        }
    }
}

Example 3: how to POST in c#

using System;
using System.Collections.Specialized;
using System.Net;

namespace API_Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare the API Endpoint URL
            string url = "URL_HERE";

            // Create a New WebClient
            WebClient client = new WebClient();

            // Create a New NameValueCollection
            NameValueCollection values = new NameValueCollection();

            // Add Data to the NameValueCollection
            values.Add("data-name", "content");

            // Upload the NameValueCollection Values to the URL
            client.UploadValues(url, values);
        }
    }
}

Example 4: c# make http request

private static readonly HttpClient client = new HttpClient();

var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");

Example 5: how make a post request c#

//You can aquire RestSharp from Nuget package manager
  RestClient restClient = 
  new RestClient(string.Format("{0}/myservice/api/endpoint", "https://exampledomain.com:88"));
  RestRequest request = new RestRequest(Method.POST);
  request.RequestFormat = DataFormat.Json;
  request.AddJsonBody(data); //data is C# model for post request
  request.AddHeader("Accept", "application/pdf");
  var result = restClient.Execute(request);