我正在尝试对New Relic运行API调用,以检索所有Synthetics监视器的列表。我在使它无法正常工作时遇到困难,只是被卡住了……尝试查看许多红宝石参考资料,但我只是没有得到它,所以希望你们能为我提供帮助!
这需要HTTPS,代理和身份验证标头:
Chef::Log.info('Retrieving New Relic Synthetics monitors')
uri = URI("https://synthetics.newrelic.com/synthetics/api/v3/monitors")
uri.headers = "x-api-key:<my_key_here>"
proxy_addr = "192.168.0.100"
proxy_port = "3200"
begin
tries ||= 3
response = JSON.parse(Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port, :use_ssl => uri.scheme == 'https') { |http|
request = Net::HTTP::Get.new uri
response = http.request request
})
raise 'ERROR: Unable to retrieve New Relic Synthetics monitors' unless response['monitors']
all_synthetics_monitors = response
rescue
if (tries -= 1) > 0
Chef::Log.warn("Retrieving New Relic Synthetics monitors: [#{uri}].. Retrying!\n")
sleep(10)
retry
else
Chef::Log.error("Retrieving New Relic Synthetics monitors: [#{uri}].. Failed!\n")
return
end
end.flatten
到目前为止,我只是重试而已,甚至无法弄清楚该API正在传递什么。我尝试在请求和响应周围运行一些“输入”,但是还没走得很远……
答案 0 :(得分:0)
想通了!
必须使用Net::HTTP.new
而不是Net::HTTP.get
:
uri = URI.parse('https://synthetics.newrelic.com/synthetics/api/v3/monitors')
begin
tries ||= 3
proxy_ipaddress = "192.168.0.100"
proxy_port = "3200"
proxy_uri = URI.parse("http://#{proxy_ipaddress}:#{proxy_port}")
http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request["x-api-key"] = "<insert_your_API_key_here>"
response = http.request(request)
all_running_synthetics_scripts = response.body.to_json
# Finish HTTP connection. -- Find out if this is necessary or not
http.finish if http.started?
raise "ERROR: Unable to retrieve New Relic Synthetics monitors, got http code #{response.response.code.to_i}" unless response.response.code.to_i == 200
rescue
if (tries -= 1) > 0
puts("Retrieving New Relic Synthetics monitors: [#{uri}].. Retrying!\n")
sleep(10)
retry
else
puts("Retrieving New Relic Synthetics monitors: [#{uri}].. Failed!\n")
return
end
end