HttpClient
in C# is a class provided by the .NET framework, specifically within the System.Net.Http
namespace, which is used for sending HTTP requests and receiving HTTP responses from a resource identified by a URI (Uniform Resource Identifier). It is an essential tool for interacting with web services and APIs from C# applications.
The class is designed to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient
instance for each request can lead to resource exhaustion due to the number of sockets that may be left open. Therefore, it's recommended to use a single or a few instances of HttpClient
for application-wide usage.
Here's an example of how to use HttpClient
to make a GET request to a web service:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
try
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
HttpResponseMessage response = await client.GetAsync("http://example.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
In this example, we define a static HttpClient
instance and use it in an asynchronous Main
method. We attempt to retrieve content from "http://example.com/" using GetAsync
, which returns an HttpResponseMessage
. This message is then checked to ensure the response status code indicates success using EnsureSuccessStatusCode()
. Finally, the response body is read as a string and output to the console.
HttpClient
supports other HTTP methods such as POST, PUT, DELETE, etc., and allows you to add headers, work with different content types, and handle request and response messages in a more granular fashion if needed. Here is an example of a POST request with JSON content:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
var product = new { Name = "Gadget", Price = 19.95 };
var json = JsonConvert.SerializeObject(product);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
// POST the JSON and process response.
HttpResponseMessage response = await client.PostAsync("http://example.com/api/products", content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
In this POST example, we serialize an object to JSON using JsonConvert.SerializeObject
, then create a StringContent
object specifying the media type as JSON. We send this content to the server using PostAsync
. If successful, we read and write the response body to the console.
Remember to always dispose of the HttpClient
instances when they are no longer needed to free up resources, although if you are following the single instance recommendation, this would typically occur when the application is closing. In .NET Core and later versions, HttpClient
also implements IHttpClientFactory
to handle the lifetimes of HttpClient
instances, which is a recommended approach to use in those environments.