make a http head request in csharp

To make an HTTP HEAD request using C#, you can use the HttpWebRequest class from the System.Net namespace. Here's an example code snippet to make an HTTP HEAD request and get the response headers:

main.cs
using System;
using System.Net;

public class HttpHeadRequestExample
{
    public static void Main(string[] args)
    {
        string url = "https://www.example.com";

        // Create the HTTP HEAD request
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "HEAD";

        try
        {
            // Get the HTTP response
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                // Print the response headers
                foreach (string key in response.Headers.AllKeys)
                {
                    Console.WriteLine("{0}: {1}", key, response.Headers[key]);
                }
            }
        }
        catch (WebException e)
        {
            // Handle exceptions
            Console.WriteLine("{0}: {1}", e.Status, e.Message);
        }
    }
}
881 chars
33 lines

In this example, the HttpWebRequest is created and set to use the HEAD method. Then, the request is sent using the GetResponse() method, which returns an HttpWebResponse object. Finally, the response headers are printed to the console using a foreach loop.

related categories

gistlibby LogSnag