带有参数的Rubys中的HTTP请求

时间:2014-01-24 08:05:20

标签: ruby curl

我正在尝试从使用https的RESTful JSON Web服务中提取数据。他们提供了一个没有问题的Curl例子;但是,我正在尝试在Ruby中运行查询,而我不是Ruby开发人员。

非常感谢任何帮助!

cURL示例:

curl -G "https://api.example.com/v1/query/" \
     -H "Accept: application/vnd.example.v1+hal+json" \
     -u "$API_KEY:$API_SECRET" \
     -d "app_id=$APP_ID" \
     -d "days=3" \
     -d "metrics=users" \
     -d "dimensions=day"

我在Ruby中尝试导致HTTPUnauthorized 401:

require 'net/https'
require 'uri'
# prepare request  
  uri = URI.parse("https://api.example.com/v1/query/")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(uri.request_uri, {
    'Accept' => 'application/vnd.example.v1+hal+json', 
    'api_key' => 'api_secret',
    'app_id' => 'app_id',
    'days' => '3',
    'metrics' => 'users',
    'dimensions' => 'day'})

  response = http.request(request)
  response.body
  response.status
  response["header-here"] # All headers are lowercase

  # Analyze the response
  if response.code != "200"
    puts "Error (status-code: #{response.code})\n#{response.body}"
    print 0
  else
    print 1
  end

**更新** 根据下面的反馈,我安装了Typhoeus并更新了请求。现在我通过了。谢谢大家!

  request = Typhoeus::Request.new(
    "https://api.example.com/v1/query/",
    userpwd: "key:secret",
    params: { 
      app_id: "appid",
      days: "3",
      metrics: "users",
      dimensions: "day" 
    },
    headers: { 
      Accept: "application/vnd.example.v1+hal+json"
    }
  )

2 个答案:

答案 0 :(得分:2)

首先你需要意识到:

'Accept' => 'application/vnd.example.v1+hal+json'

是标题,而不是参数。

此外:

$API_KEY:$API_SECRET  

是基本的HTTP身份验证,而不是参数。

然后,接受我的建议并使用更好的Ruby HTTP客户端:

<强>更新

从IRB尝试以下内容:

Typhoeus::Config.verbose = true # this is useful for debugging, remove it once everything is ok.
request = Typhoeus::Request.get(
  "https://api.example.com/v1/query/",
   userpwd: "key:secret",
   params: { 
     app_id: "appid",
     days: "3",
     metrics: "users",
     dimensions: "day" 
   },
   headers: { 
     Accept: "application/vnd.example.v1+hal+json"
   }
 )

答案 1 :(得分:1)

curl -u发送Authorization标头。所以你的'api_key' => 'api_secret'应该替换为这个(再次,它的http标题,而不是参数)。

"Authorization" => "Basic ".Base64.encode64("api_key:api_secret")
## require "base64"