How to send web request to URL in C#
By FoxLearn 1/9/2025 4:38:06 AM 63
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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#