Using Ruby, how do I convert the short URLs (tinyURL, bitly etc) to the corresponding long URLs?
Asked
Active
Viewed 3,495 times
3 Answers
14
I don't use Ruby but the general idea is to send an HTTP HEAD request to the server which in turn will return a 301 response (Moved Permanently) with the Location
header which contains the URI.
HEAD /5b2su2 HTTP/1.1
Host: tinyurl.com
Accept: */*
RESPONSE:
HTTP/1.1 301 Moved Permanently
Location: http://stackoverflow.com
Content-type: text/html
Date: Sat, 23 May 2009 18:58:24 GMT
Server: TinyURL/1.6
This is much faster than opening the actual URL and you don't really want to fetch the redirected URL. It also plays nice with the tinyurl service.
Look into any HTTP or curl APIs within ruby. It should be fairly easy.

aleemb
- 31,265
- 19
- 98
- 114
-
And to be clear, this is an effective method to find the destination of any redirect. – John Gietzen May 23 '09 at 19:14
-
5You may want to check the header of any given location as well, so you can follow a chain of redirects. – rampion May 23 '09 at 23:51
11
You can use the httpclient rubygem to get the headers
#!/usr/bin/env ruby
require 'rubygems'
require 'httpclient'
client = HTTPClient.new
result = client.head(ARGV[0])
puts result.header['Location']

slillibri
- 731
- 5
- 6
-
So condensing the last three lines into one is useful for me: `longUrl = HTTPClient.new.head("http://bit.ly/GFscreener12").header['Location'][0]` – Marcos Feb 17 '12 at 22:12
2
There is a great wrapper for the bitly API in Python available here: http://code.google.com/p/python-bitly/
So there must be something similar for Ruby.

yoav.aviram
- 1,802
- 15
- 19