使用 REST_CLIENT 发起请求,相当于 curl 请求

make a request using REST_CLIENT, equivalent to a curl request

我正在尝试使用 rest_client 发出此 curl 请求,但我总是出错。我该怎么做?

curl 请求:它运行良好并从 yahoo 返回访问令牌。

curl -u "<consumer_key>:<consumer_secret>" -d "grant_type=authorization_code&code=<code>&redirect_uri=<redirect_uri>" https://api.login.yahoo.com/oauth2/get_token

我正在努力完成的 rest_client 请求是:

# get token
  yahoo_url = "https://api.login.yahoo.com/oauth2/get_token/"
  response = RestClient::Request.new(
      :method => :get,
      :url => yahoo_url,
      :client_id => $consumer_id,
      :client_secret => $consumer_secret,
      :headers => { :accept => :json,:content_type => :json},
      :params => {'grant_type' => 'authorization_code', 'code' => code, 'redirect_uri' => $yahoo_redirect_url}
  ).execute
  results = JSON.parse(response.to_str)
  puts "RESULTS: #{results}"

或这个:

response = RestClient.get 'https://dj0yJmk9Q1RKU2xclient_id:be49966a23db7_client_secretb@api.login.yahoo.com/oauth2/get_token', {:params => {'grant_type' => 'authorization_code', 'code' => code, 'redirect_uri' => $yahoo_redirect_url}}

任何帮助或建议甚至更好的方法都将不胜感激,在此先感谢。

请求必须是 HTTP POST 而不是 HTTP GET 并传递如下参数:

# POST or PUT with a hash sends parameters as a urlencoded form body
# RestClient.post 'http://example.com/resource', :param1 => 'one'

所以:

response = RestClient.post 'https://dj0yJmk9Q1RKU2xclient_id:be49966a23db7_client_secretb@api.login.yahoo.com/oauth2/get_token', :grant_type => 'authorization_code', :code => code, :redirect_uri => $yahoo_redirect_url