Skip to content

Instantly share code, notes, and snippets.

@komiya-atsushi
Created April 12, 2013 19:45
Show Gist options
  • Save komiya-atsushi/5374580 to your computer and use it in GitHub Desktop.
Save komiya-atsushi/5374580 to your computer and use it in GitHub Desktop.
Ruby で Twitter API の Application-only authentication のトークンを取得する方法 ref: http://qiita.com/items/b3e6351877d89ce74691
{"token_type":"bearer","access_token":"ここにトークンが設定される"}
Authorization: Bearer アクセストークン
require 'net/https'
require 'base64'
require 'uri'
Net::HTTP.version_1_2
CONSUMER_KEY = 'ここに consumer_key を設定する'
CONSUMER_SECRET = 'ここに consumer_secret を設定する'
bearer_token = "#{CONSUMER_KEY}:#{CONSUMER_SECRET}"
encoded_bearer_token = Base64.strict_encode64(bearer_token)
url = URI.parse("https://api.twitter.com/oauth2/token")
https = Net::HTTP.new(url.host, 443)
https.use_ssl = true
https.start do
header = {}
header["Authorization"] = "Basic #{encoded_bearer_token}"
header["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
req = Net::HTTP::Post.new(url.path, header)
req.body = "grant_type=client_credentials"
resp = https.request(req)
puts resp.body
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment