我正在访问不同的服务器以获取数据,我在不同的类中尝试了不同的方法,使用基本的 http::net、curb、rest-client 和 open-uri
(1) 一般如何衡量 Ruby/Rails 的性能?(2) 你认为哪种方法更快?
来自所有 4 种不同方法的示例代码:
url = "..."
begin
io_output = open(url, :http_basic_authentication => [@user_id, @user_password])
rescue => e
error = e.message #for debugging return this
return '-'
else
output = io_output.read
或者
require 'net/https'
uri = URI.parse("...")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
data = http.get(uri.request_uri) #http request status
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)
或者
require 'curb'
url = "..."
c = Curl::Easy.new(url) do |curl|
curl.headers["Content-type"] = "application/json"
curl.headers["Authorization"] = "Token ..."
end
c.perform
puts c.body_str
或者
url = "..."
resource = RestClient::Resource.new(url,
:headers => { :Authorization => "Token ...",
:content_type => "application/json"})
begin
output = resource.get
rescue => e
error = e.message #for debugging return this
return '-'
else ...
end