http request in csharp

Here's an example of how to perform an HTTP request in C# using HttpWebRequest and HttpWebResponse classes:

main.cs
string url = "https://example.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseBody = "";

using (Stream responseStream = response.GetResponseStream())
{
    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
    responseBody = reader.ReadToEnd();
}

response.Close();
418 chars
15 lines

Alternatively, you can use the HttpClient class introduced in .NET Framework 4.5 that simplifies the process:

main.cs
using System.Net.Http;

string url = "https://example.com";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
259 chars
8 lines

gistlibby LogSnag