开发者

Obtain forwarded URL from a source URL?

What is a good way to obtain the end URL if given a URL that is being forwarded to another URL?

For example, if I had the shortened URL: http://bit.ly/900913, what is a good way to determine that this ultimately forwards to http://www.google.com?

I'm usi开发者_JS百科ng javascript. I'm unsure if this can be done somehow using jQuery (doubtful since the end URL probably isn't returning jsonp content) or if there is some kind of web service that I can use.

Thanks!


For bit.ly specifically, you can use the bit.ly API to make a JSONP call using JavaScript to expand the bit.ly URL(s) in question.

Specifically, you'd use the v3/expand call.

Pseudo-code:

var bitlyurl = "http://bit.ly/900913";
$.getJSON("http://api.bitly.com/v3/expand?shortUrl=" + encodeURIComponent(bitlyurl)+"&apikey=...&callback=?", function( bitlydata ){

     var endurl  = bitlydata.data.expand[0] //looks like this is where the end URL would point
});

Alternately, you could follow the URL on your own server, and use AJAX to check it's values.

So, you'd pass it a URL ($.get("/follow?url="+bitlyurl,function(data){var endurl = data.Location;});, and make a HEAD call to the URL to see where the Location points.

Here's the basics of how you'd do it in PHP:

<?php
$headers = get_headers($_GET["url"],1);
echo json_encode($headers);
?>

Just for fun, I implemented a live end-point on App Engine to check where a URL points. Feel free to use it! The base URL is followtheredirect.appspot.com, and it requires a url parameter and a callback parameter, and returns a location key on the resulting object, when successful.

Sample code:

$.getJSON("http://followtheredirect.appspot.com/?url="+encodeURIComponent('http://bitly.com/hhN7Ol')+"&callback=?",function(data){
    var location = data.location;
});

Let me know if you find any bugs :) it might be a bit messy...


Bitly provides a preview service. If you visit http://bit.ly/900913- (notice the hyphen at the end), you'll get a response with the full URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜