Created
May 8, 2012 14:10
-
-
Save nicklegr/2635399 to your computer and use it in GitHub Desktop.
Rubyで、さまざまなサービスの短縮URLを展開する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!ruby -Ku | |
require 'net/http' | |
require 'uri' | |
require 'json' | |
require 'pp' | |
class ShortURL | |
# 普通のURLを渡した場合、そのまま返す | |
def self.expand(short_url) | |
# http://longurl.org/api | |
connection = Net::HTTP.new('api.longurl.org') | |
connection.start do |http| | |
headers = { | |
'Referer' => '', | |
'User-Agent' => '' | |
} | |
path = "/v2/expand?url=#{URI.encode(short_url)}&format=json" | |
response = http.request_get(path, headers) | |
data = JSON.parse(response.body) | |
if data['messages'] | |
raise data['messages'][0]['message'] | |
end | |
data['long-url'] | |
end | |
end | |
end | |
__END__ | |
# test | |
pp ShortURL.expand('http://is.gd/w') | |
pp ShortURL.expand('http://www.google.co.jp') | |
pp ShortURL.expand('zxsdzsdfzdf') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment