Ruby 未定义的局部变量或方法“http';对于主:对象(NameError)
文件:Ruby 未定义的局部变量或方法“http';对于主:对象(NameError),ruby,Ruby,文件:nethttp.rb require 'uri' require 'net/http' http.verify_mode = OpenSSL::SSL::VERIFY_NONE uri = URI('http://localhost/events',:headers => headers) res = Net::HTTP.get_response(uri) puts res.body if res.is_a?(Net::HTTPSuccess) 我收到错误信息: main:Ob
nethttp.rb
require 'uri'
require 'net/http'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
uri = URI('http://localhost/events',:headers => headers)
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)
我收到错误信息:
main:Object的未定义局部变量或方法“http”(NameError)
您使用的是局部变量
http
,它在代码中的任何地方都没有声明。如果要创建Net::HTTP的实例,需要使用“new”方法:
但您可能需要考虑使用<代码> NET:HTTP.Stase,它打开一个连接并将其传递给块:
require 'uri'
require 'net/http'
uri = URI('http://localhost/events')
# Opens a persisent connection to the host
Net::HTTP.start(uri.host, uri.port, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
headers = { "X-FOO" => "Bar" }
request = http.get(uri)
headers.each do |key, value|
request[key] = value
end
response = http.request(request)
# consider using a case statement
if response.is_a?(Net::HTTPSuccess)
puts response.body
else
# handle errors
end
end
我试图通过库nethttp使用API,但无法修复此错误:您正在使用名为
http
的局部变量,但未将其设置在任何位置。http
未定义。这就是错误告诉你的。我不确定您希望在这里发生什么,但也许您想在uri=…
代码行下面放置类似http=Net::http.new(uri.host,uri.port)
的内容?然后使用http.get
而不是Net::http.get\u response
?另一方面,值得注意的是,2021年的Net::http仍然没有可以传递要添加到请求中的头哈希的方法。这可能是整个Ruby StdLib中最尴尬的部分。
require 'uri'
require 'net/http'
uri = URI('http://localhost/events')
# Opens a persisent connection to the host
Net::HTTP.start(uri.host, uri.port, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
headers = { "X-FOO" => "Bar" }
request = http.get(uri)
headers.each do |key, value|
request[key] = value
end
response = http.request(request)
# consider using a case statement
if response.is_a?(Net::HTTPSuccess)
puts response.body
else
# handle errors
end
end