How to read response from url using HttpClient in C#

28 March 2022 | Viewed 16403 times

System.Net.Http namespace provides a class (HttpClient) for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

HttpClient is useful when downloading large amounts of data (50 megabytes or more), and the app should stream those downloads and not use the default buffering. If the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.

C# Code
string ReadResponseFromUrl(string url)
{
var httpClientHandler = new HttpClientHandler();
var httpClient = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(url)
};
using (var response = httpClient.GetAsync(url))
{
string responseBody = response.Result.Content.ReadAsStringAsync().Result;
return responseBody;
}
}

The HttpClient is a high-level API that wraps the lower-level functionality available on each platform where it runs. On each platform, HttpClient tries to use the best available transport:
HttpClient is intended to be instantiated once and re-used throughout the life of an application.
PreviousNext