c# httpclient post code example
Example 1: c# post get request
using System.Net.Http;
HttpClient client = new HttpClient();
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();
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
Example 2: c# getasync response
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
var finalResult = await GetResponseString(text);
Example 3: example HttpClient c# Post
public async string Example()
{
var pocoObject = new
{
Name = "John Doe",
Occupation = "gardener"
};
string json = JsonConvert.SerializeObject(pocoObject);
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = await response.Content.ReadAsStringAsync();
client.Dispose();
return result;
}
Example 4: httpclient post c# json
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(ticket);
var content = new StringContent(json, Encoding.UTF8, "application/json");
await httpClient.PostAsync("https://address.com", content);
Example 5: webclient c# example post
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
Example 6: 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);
}
}
}