How to send web request to URL in C#
By FoxLearn 1/9/2025 4:38:06 AM 186
WebRequest
(older method), HttpClient
(modern and preferred method), or HttpWebRequest
(more control over HTTP settings).
Using WebRequest to send a GET request
WebRequest
is an older API but can still be used if you need to support legacy code. It is more generic and can be used for various protocols, not just HTTP.
var url = "https://example.com"; // Sending a web request to the URL to fetch data var request = WebRequest.Create(url); request.Method = "GET"; var responseData = ""; using (var webResponse = request.GetResponse()) { using (var responseStream = webResponse.GetResponseStream()) { using (var reader = new StreamReader(responseStream)) { responseData = reader.ReadToEnd(); } } }
Using HttpClient to make a GET request
HttpClient
is the most commonly used method for making web requests in modern C#. It is part of the System.Net.Http
namespace and provides a simpler and more efficient way to send requests and handle responses.
using System.Net.Http; using System.Net.Http.Headers; HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://example.com/"); // Set the Accept header to receive JSON data client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("api/data").Result; // Adjust the controller endpoint here if (response.IsSuccessStatusCode) { var responseContent = response.Content.ReadAsStringAsync().Result; Console.WriteLine(responseContent); } else { string errorMessage = $"Error: {response.StatusCode} {response.ReasonPhrase}"; Console.WriteLine(errorMessage); }
In the second example, we are using the HttpClient class, which is often considered more modern and flexible than WebRequest
. It’s commonly used for interacting with RESTful APIs and other web services.
Both methods are essential for making web requests and retrieving data, and you can choose the one that suits your project requirements.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#