ac-lap
ac-lap

Reputation: 1653

How do I get the destination URL of a shortened URL?

I have an API (https://www.readability.com/developers/api/parser#idm386426118064) to extract the contents of the webapges, but on passing a shortened url or an url that redirects to other, it gives error.

I am developing windows phone 8.1 (xaml) app. Is there any way to get the destination url in c# or any work around?

eg url - http://www.bing.com/r/2/BB7Q4J4?a=1&m=EN-IN

Upvotes: 1

Views: 1183

Answers (3)

User 12345678
User 12345678

Reputation: 7804

You could intercept the Location header value before the HttpClient follows it like this:

using (var handler = new HttpClientHandler())
{
    handler.AllowAutoRedirect = false;
    using (var client = new HttpClient(handler))
    {
        var response = await client.GetAsync("shortUrl");
        var longUrl = response.Headers.Location.ToString();
    }
}

This solution will always be the most efficient because it only issue one request.

It is possible however, that the short url will reference another short url and consequently cause this method to fail.

An alternative solution would be to allow the HttpClient to follow the Location header value and observe the destination:

using (var client = new HttpClient())
{
    var response = client.GetAsync("shortUrl").Result;
    var longUrl = response.RequestMessage.RequestUri;
}

This method is both terser and more reliable than the first.

The drawback is that this code will issue two requests instead of one.

Upvotes: 5

Tyress
Tyress

Reputation: 3653

You can get the ResponseUri from GetResponse():

string redirectedURL = WebRequest.Create("http://www.bing.com/r/2/BB7Q4J4?a=1&m=EN-IN")
                                 .GetResponse()
                                 .ResponseUri
                                 .ToString();

Interesting article, by the way.

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67175

You need to inspect the headers returned from the URL.

If you get HTTP return codes 301 or 302, then you are being notified that the page is redirecting you to another URL.

See http://www.w3.org/Protocols/HTTP/HTRESP.html for more details about HTTP return codes.

Upvotes: -1

Related Questions