Summary
Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified over a network.
The HttpClient
class is an IDisposable
object. It is recommended that you use a single instance of HttpClient
for the lifetime of an application. For more information, see HttpClient lifecycle management.
The HttpClient
class implements the modern, more performant way of making HTTP requests. It supports asynchronous operations and is designed for extensibility.
Syntax
public sealed class HttpClient : IDisposable
Example
The following code example demonstrates how to use the HttpClient
class to send a GET request and display the response content.
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :" + e.Message);
}
}
}
}