httpclient get c# code example
Example 1: 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 2: 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 3: httpclient c# sample
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}