Last active
November 18, 2016 23:50
-
-
Save cyu/57d1253f18779af74899 to your computer and use it in GitHub Desktop.
Revisions
-
cyu renamed this gist
May 6, 2014 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
cyu created this gist
May 6, 2014 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,47 @@ # https://dev.twitter.com/docs/auth/application-only-auth require 'open-uri' require "base64" require 'net/http' require 'json' CONSUMER_KEY = 'MY_CONSUMER_KEY' CONSUMER_SECRET = 'MY_CONSUMER_SECRET' key_encoded = URI::encode(CONSUMER_KEY) secret_encoded = URI::encode(CONSUMER_SECRET) key_secret_combined = [key_encoded, secret_encoded].join(':') key_secret_encoded = Base64.encode64(key_secret_combined).gsub("\n", '') uri = URI('https://api.twitter.com/oauth2/token') req = Net::HTTP::Post.new(uri) req['Content-Type' ] = 'application/x-www-form-urlencoded;charset=UTF-8' req['Authorization'] = "Basic #{key_secret_encoded}" req.form_data = { :grant_type => 'client_credentials' } response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http| http.request(req) end bearer_token = nil if parsed_response = JSON.parse(response.body) if parsed_response['token_type'] == 'bearer' bearer_token = parsed_response['access_token'] end end puts bearer_token # example of how to use the token uri = URI('https://api.twitter.com/1.1/statuses/user_timeline.json?count=4&screen_name=scoutmob') req = Net::HTTP::Get.new(uri) req['Authorization'] = "Bearer #{bearer_token}" http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true response = http.start { |http| http.request(req) }