Question

I need to get the url of the final destination of a shortened url. At the moment I am doing the following which seems to work:

        var request = WebRequest.Create(shortenedUri);
        var response = request.GetResponse();
        return response.ResponseUri;

But can anyone suggest a better way?

Was it helpful?

Solution 2

You do need to make an HTTP request - but you don't need to follow the redirect, which WebRequest will do by default. Here's a short example of making just one request:

using System;
using System.Net;

class Test
{
    static void Main()
    {
        string url = "http://tinyurl.com/so-hints";
        Console.WriteLine(LengthenUrl(url));
    }

    static string LengthenUrl(string url)
    {
        var request = WebRequest.CreateHttp(url);
        request.AllowAutoRedirect = false;
        using (var response = request.GetResponse())
        {
            var status = ((HttpWebResponse) response).StatusCode;
            if (status == HttpStatusCode.Moved ||
                status == HttpStatusCode.MovedPermanently)
            {
                return response.Headers["Location"];
            }
            // TODO: Work out a better exception
            throw new Exception("No redirect required.");
        }
    }
}

Note that this means if the "lengthened" URL is itself a redirect, you won't get the "final" URI as you would in your original code. Likewise if the lengthened URL is invalid, you won't spot that - you'll just get the URL that you would have redirected to. Whether that's a good thing or not depends on your use case...

OTHER TIPS

If this shortened url is generated by some online service provider it is only this service provider that is storing the mapping between the short and the actual url. So you need to query this provider by sending an HTTP request to it, exactly as you did. Also don't forget to properly dispose IDisposable resources by wrapping them in using statements:

var request = WebRequest.Create(shortenedUri);
using (var response = request.GetResponse())
{
    return response.ResponseUri;
}

If the service provider supports the HEAD verb you could also use this verb and read the Location response HTTP header which must be pointing to the actual url. As an alternative you could set the AllowAutoRedirect property to false on the request object and then read the Location response HTTP header. This way the client won't be redirecting to the actual resource and getting the entire response body when you are not interested in it.

Of course the best way to do this would be if your online service provider offers an API that would allow you to directly give you the actual url from a short url.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top