将Curl转换为Ruby(New Relic API)

时间:2016-08-24 13:23:24

标签: ruby curl newrelic

我对红宝石极其陌生,但我正在玩它。有人可以帮我把这个curl命令翻译成Ruby吗?

我一直在努力调整其他红宝石示例以满足我的需求。

  curl -X GET 'https://api.newrelic.com/v2/servers.json' \
     -H 'X-Api-Key:12345689' -i \
     -G -d 'filter[host]=server1' 

Ruby代码:

require 'net/http'

uri = URI.parse('https://api.newrelic.com/v2/servers.json')
request = Net::HTTP::Get.new uri.request_uri

res = Net::HTTP.start(uri.host, uri.port,
     :use_ssl => uri.scheme == 'https') {|http| http.request request}

request.initialize_http_header({'X-Api-Key' => '12345689'})
request.initialize_http_header({'Accept' => 'application/json'})
request.initialize_http_header({'Content-Type' => 'application/json'})
request.set_form_data({"filter[host]" => "server1"})


response = res.request(request)

错误讯息:

test.rb:16:in `<main>': undefined method `request' for #<Net::HTTPUnauthorized 401 Unauthorized readbody=true> (NoMethodError)

2 个答案:

答案 0 :(得分:2)

应该是这样的:

require 'net/http'

uri = URI('https://api.newrelic.com/v2/servers.json')
uri.query = URI.encode_www_form({ 'filter[host]' => 'server1' })
req = Net::HTTP::Get.new(uri)
req['X-Api-Key'] = '123456789'

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true
response =  http.request(req)
p response.read_body

答案 1 :(得分:1)

在Ruby中,您可以使用反引号(`)简单地获取命令的输出,您只需要转义特殊字符,就像在每个其他字符串中一样。所以它会是:

`curl -X GET 'https://api.newrelic.com/v2/servers.json' -H 'X-Api-Key:12345689' -i -G -d 'filter[host]=server1'`