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

时间:2015-01-16 14:05:22

标签: ruby-on-rails ruby curl httpclient rest-client

我正在尝试使用rest_client进行此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}}

任何帮助或建议,甚至更好的工作都将受到赞赏,提前谢谢。

1 个答案:

答案 0 :(得分:2)

请求必须是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