Created
July 6, 2013 07:14
-
-
Save komasaru/5939019 to your computer and use it in GitHub Desktop.
Ruby script to shorten a long url to a short url by bitly API V3.
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
#********************************************* | |
# BitLy API v3 で ロング URL を短縮する。 | |
# - API キー認証、OAuth 認証両方対応 | |
# (インスタンス化部分で切り替え可能) | |
#********************************************* | |
# | |
require 'net/http' # API キー認証用 | |
require 'net/https' # OAuth 認証用 | |
require 'cgi' | |
require 'nkf' | |
require 'json' | |
# API キー認証用 | |
DOMAIN = "api.bitly.com" # (or "api-ssl.bitly.com") | |
USER = "hoge" | |
API_KEY = "R_XXXXXXXXXXXXXXXXXXXXXXX" | |
# OAuth 認証用 | |
DOMAIN_SSL = "api-ssl.bitly.com" | |
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXX" | |
# API キー認証用クラス | |
class BitlyApikey | |
def shorten(url) | |
params = "/v3/shorten?login=#{USER}&apiKey=#{API_KEY}&longURL=#{CGI.escape(NKF.nkf("-w -m0", url))}" | |
http = Net::HTTP.new(DOMAIN, 80) | |
res = http.start {http.get(params)} | |
return JSON.parse(res.body) | |
end | |
end | |
# OAuth 認証用クラス | |
class BitlyOauth | |
def shorten(url) | |
params = "/v3/shorten?access_token=#{TOKEN}&longURL=#{CGI.escape(NKF.nkf("-w -m0", url))}" | |
https = Net::HTTP.new(DOMAIN_SSL, 443) | |
https.use_ssl = true | |
https.verify_mode = OpenSSL::SSL::VERIFY_PEER | |
res = https.start {https.get(params)} | |
return JSON.parse(res.body) | |
end | |
end | |
# インスタンス化 | |
bitly = BitlyApikey.new # API キー認証用 | |
# bitly = BitlyOauth.new # OAuth 認証用 | |
# URL 短縮 | |
res = bitly.shorten("http://www.google.com/") | |
# 結果表示 | |
puts "status_code: #{res["status_code"]}" | |
puts "status_txt : #{res["status_txt"]}" | |
if res["status_code"] == 200 | |
puts "long_url : #{res["data"]["long_url"]}" | |
puts "url : #{res["data"]["url"]}" | |
puts "hash : #{res["data"]["hash"]}" | |
puts "global_hash: #{res["data"]["global_hash"]}" | |
puts "new_hash : #{res["data"]["new_hash"]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment