send http request in csharp

To send an HTTP request in C#, you can use either the HttpWebRequest or HttpClient class. Here's an example of each:

Using HttpWebRequest:

main.cs
using System;
using System.IO;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseText = reader.ReadToEnd();
            Console.WriteLine(responseText);
        }
    }
}
490 chars
19 lines

In this example, we first create an instance of the HttpWebRequest class by passing in the URL we want to request. We then use the GetResponse method to actually send the request and get the response. Finally, we read the response stream and output the response text to the console.

Using HttpClient:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("http://www.example.com");
        string responseText = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseText);
    }
}
390 chars
16 lines

In this example, we create an instance of the HttpClient class, and then use the GetAsync method to send an HTTP GET request to the specified URL. We then read the content of the response and output it to the console.

Note that in this example, we're using the await keyword to asynchronously wait for the response to be returned. This allows us to make the HTTP request without blocking the calling thread.

gistlibby LogSnag