使用oAuth令牌进行API调用

Ala*_*ano 8 ruby oauth

我想在Ruby中提出oAuth请求.我浏览了一些例子,但没有一个用于oauth_token_secret and oauth_token提出请求,他们只使用consumer_keyconsumer_secret获取oauth_token_secretoauth_token.但是我已经有oauth_token_secretoauth_token.

例如,我尝试使用这个

require 'rubygems'
require 'oauth'
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
                               {
                                 :site=> "https://www.google.com",
                                 :scheme=> :header,
                                 :http_method=> :post,
                                 :request_token_path => "/accounts/OAuthGetRequestToken",
                                 :access_token_path => "/accounts/OAuthGetAccessToken",
                                 :authorize_path=> "/accounts/OAuthAuthorizeToken",
                                 :signature_method=>"RSA-SHA1"},
                               # :private_key_file=>PATH_TO_PRIVATE_KEY
                               )

request_token = consumer.get_request_token()

puts "Visit the following URL, log in if you need to, and authorize the app"
puts request_token.authorize_url
puts "When you've authorized that token, enter the verifier code you are assigned:"

verifier = gets.strip

puts "Converting request token into access token..."

access_token=request_token.get_access_token(:oauth_verifier => verifier)

puts "access_token.token --> #{access_token.token}" # But I initially have it
puts "access_token.secret --> #{access_token.secret}" # But I initially have it
Run Code Online (Sandbox Code Playgroud)

就我而言,有4个密钥:

consumer_key = "anonymous"
consumer_secret = "anonymous"
oauth_token_secret = "fdsfdsfdfdsfds"
oauth_token = "fdsfdsfdfdsfdsdsdsdsdsdsds"
Run Code Online (Sandbox Code Playgroud)

所以我需要做的是,使用一些额外的get参数和oAuth令牌向某个url发出API请求并获得答案.

我如何在Ruby中做到这一点?

old*_*god 12

#!/usr/bin/env ruby
require 'rubygems'
require 'oauth'
require 'json'
Run Code Online (Sandbox Code Playgroud)

你需要获得access_token(OAuth::AccessToken).

# Initialisation based on string values:
consumer_key = 'AVff2raXvhMUxFnif06g'
consumer_secret = 'u0zg77R1bQqbzutAusJYmTxqeUpWVt7U2TjWlzbVZkA'
access_token = 'R1bQqbzYm0zg77tAusJzbVZkAVt7U2T'
access_token_secret = 'sVbVZkAt7U2TjWlJYmTxqR1bQqbzutAuWzeUpu0zg77'

@consumer = OAuth::Consumer.new(consumer_key, consumer_secret, {:site=>'http://my.site'})
accesstoken = OAuth::AccessToken.new(@consumer, access_token, access_token_secret)
Run Code Online (Sandbox Code Playgroud)

获得OAuth::AccessToken对象后,您可以:

json_response = accesstoken.get('/photos.xml')
# or
json_response = accesstoken.post(url, params_hash)
Run Code Online (Sandbox Code Playgroud)

等等

响应是一个json对象.要阅读它,您可以:

response = JSON.parse(json_response.body)
# which is a hash
# you just access content like
id = response["id"]
Run Code Online (Sandbox Code Playgroud)