Is it possible to display or trace the URL's when there are redirects?

207 views Asked by At

I have a URL that is a tracking URL, and when I visit the URL it redirects a few times until it finally lands URL that doesn't redirect.

Is it possible to write a function that will follow the redirects and just output them to the console?

1

There are 1 answers

0
rfmodulator On
class Program
{
    private static readonly int MAX_REDIRECTS = 10;
    private static readonly string NL = Environment.NewLine;

    static void Main(string[] args)
    {
        DoRequest(new Uri("http://google.com/"));

        Console.ReadLine();
    }

    public static void DoRequest(Uri uri, int i = 0)
    {
        var request = WebRequest.CreateHttp(uri);
        request.AllowAutoRedirect = false;
        // Optional. May not work with all servers.
        //request.Method = WebRequestMethods.Http.Head;

        Uri redirectUri = null;

        try
        {
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var httpStatus = (int)response.StatusCode;

                if (httpStatus >= 300 && httpStatus < 400)
                {
                    if (response.Headers[HttpResponseHeader.Location] != null)
                    {
                        redirectUri = new Uri(uri, response.Headers[HttpResponseHeader.Location]);
                    }

                    Console.WriteLine($"HTTP {httpStatus}\t{uri} ---> {redirectUri}");

                    if (++i >= MAX_REDIRECTS)
                    {
                        Console.WriteLine($"Limit of {MAX_REDIRECTS} redirects reached!{NL}");
                        return;
                    }
                }
                else
                {
                    Console.WriteLine($"HTTP {httpStatus}\t{uri}{NL}");
                }
            }
        }
        catch (Exception ex)
        {
            if (ex is WebException wex)
            {
                if (wex.Response is HttpWebResponse resp)
                {
                    Console.WriteLine($"HTTP {(int)resp.StatusCode}\t{uri}{NL}");
                    return;
                }
            }

            Console.WriteLine($"Failed!\t\t{uri}\t{ex.Message}{NL}");
        }

        if (redirectUri != null)
        {
            DoRequest(redirectUri, i);
        }
    }
}

The HEAD method isn't required, but for servers that will respond to it, it avoids sending the entire content (when not redirected, of course).