HTTP Requests in C# using HttpClient
Introduction of HttpClient:
In software development, interacting with web servers and consuming APIs is a common requirement for many applications. Whether you're building a web application, a mobile app, or a desktop program, the ability to send and receive HTTP requests is fundamental to integrating with external services and fetching data from remote sources. HttpClient Introduced as part of the .NET Framework and later included in .NET Core and .NET. The HttpClient class, which provides a flexible and straightforward way to send and receive HTTP requests. In this guide we'll covering everything from making basic GET requests to handling more complex scenarios like authentication and error handling.
Supported Versions and Frameworks:
.NET Framework: HttpClient was introduced in .NET Framework 4.5 and is available in later versions.
.NET Core: HttpClient is supported in all versions of .NET Core, starting from .NET Core 1.0.
Getting Started with HttpClient:
Let’s start with the basics. HttpClient is part of the System.Net.Http namespace, which means you need to include the following namespace at the beginning of your code file:
To create an instance of HttpClient, you can simply do:
With above HttpClient object, you're ready to start making HTTP requests.
Preparing GET Requests:
The simplest type of HTTP request is a GET request, which retrieves data from a server. Here's how you can make a GET request using HttpClient:
In above code snippet, we use the GetAsync method to send a GET request to the specified URL. We then check if the response indicates success (status code 200-299) before reading the response body.
Preparing POST Requests:
POST requests are commonly used for sending data to a server, such as submitting a form or creating a new resource. Here's how you can make a POST request with HttpClient:
In above example, we create a StringContent object containing the data to be sent in the request body, and then use the PostAsync method to send the POST request.
Advanced Features:
HttpClient provides many advanced features, such as support for authentication, timeouts, headers and more. Here's a brief overview of some of these features:
Authentication: You can set credentials for basic authentication using the DefaultRequestHeaders.Authorization property.
Timeouts: You can set a timeout for the entire request using the Timeout property.
Headers: You can add custom headers to the request using the DefaultRequestHeaders.Add method.
Methods:
HttpClient provides below methods for sending HTTP requests:
GetAsync (Uri): Sends a GET request to the specified Uri.
PostAsync (Uri, HttpContent): Sends a POST request to the specified Uri with the specified HttpContent.
PutAsync (Uri, HttpContent): Sends a PUT request to the specified Uri with the specified HttpContent.
DeleteAsync (Uri): Sends a DELETE request to the specified Uri.
SendAsync (HttpRequestMessage): Sends an HTTP request message asynchronously.
GetStringAsync (Uri): Sends a GET request to the specified Uri and returns the response body as a string.
GetByteArrayAsync (Uri): Sends a GET request to the specified Uri and returns the response body as a byte array.
PostAsJsonAsync (Uri, Object): Sends a POST request to the specified Uri with the serialized JSON representation of an object.
Properties:
HttpClient contains properties to configure behavior:
BaseAddress: Gets or sets the base address of URI (Uniform Resource Identifier) of the Internet resource used when sending requests. When sending an HttpRequestMessage with a relative Uri, the message Uri will be added to the BaseAddress property to create an absolute Uri.
DefaultRequestHeaders: The DefaultRequestHeaders property represents the headers that an app developer can set.
Timeout: Gets or sets the time-out value in milliseconds for the HttpClient to wait before timing out the request.
Usage:
Below is a practical example demonstrating the usage of HttpClient:
Above code snippet demonstrates creating an HttpClient instance, setting base address and headers, making a GET request, and handling the response.
HttpClient in C# is a versatile tool for handling HTTP requests efficiently, and understanding its methods, constructors, properties, and extensions allows developers to utilize it effectively in their applications.
Take the first step towards data-led growth by partnering with MSA Infotech. Whether you seek tailored solutions or expert consultation, we are here to help you harness the power of data for your business. Contact us today and let’s embark on this transformative data adventure together. Get a free consultation today!
We utilize data to transform ourselves, our clients, and the world.
Partnership with leading data platforms and certified talents