自动获取请求的默认端口
Automatically get the default port for request
我目前有以下代码:
if protocol == 'http'
port = Net::HTTP.http_default_port()
endpoint = Net::HTTP.new(host, port)
else
port = Net::HTTP.https_default_port()
endpoint = Net::HTTP.new(host, port)
endpoint.use_ssl = true
end
request = Net::HTTP::Get.new("/item/#{item}")
request['Authorization'] = "Bearer #{key}"
response = endpoint.request(request)
有没有办法简化这个,这样我就不必自己决定要使用的默认端口?
您将使用 ruby 的动态调度。
port = Net::HTTP.send("#{protocol}_default_port")
endpoint = Net::HTTP.new(host, port)
endpoint.use_ssl = protocol == 'https'
request = Net::HTTP::Get.new("/item/#{item}")
request['Authorization'] = "Bearer #{key}"
response = endpoint.request(request)
或更优雅的方式:
path = URI('https://example.com')
Net::HTTP.start(path.host, path.port, use_ssl: path.scheme == 'https') do |http|
request = Net::HTTP::Get.new path
request['Authorization'] = "Bearer #{key}"
response = http.request(request)
end
我目前有以下代码:
if protocol == 'http'
port = Net::HTTP.http_default_port()
endpoint = Net::HTTP.new(host, port)
else
port = Net::HTTP.https_default_port()
endpoint = Net::HTTP.new(host, port)
endpoint.use_ssl = true
end
request = Net::HTTP::Get.new("/item/#{item}")
request['Authorization'] = "Bearer #{key}"
response = endpoint.request(request)
有没有办法简化这个,这样我就不必自己决定要使用的默认端口?
您将使用 ruby 的动态调度。
port = Net::HTTP.send("#{protocol}_default_port")
endpoint = Net::HTTP.new(host, port)
endpoint.use_ssl = protocol == 'https'
request = Net::HTTP::Get.new("/item/#{item}")
request['Authorization'] = "Bearer #{key}"
response = endpoint.request(request)
或更优雅的方式:
path = URI('https://example.com')
Net::HTTP.start(path.host, path.port, use_ssl: path.scheme == 'https') do |http|
request = Net::HTTP::Get.new path
request['Authorization'] = "Bearer #{key}"
response = http.request(request)
end