自动获取请求的默认端口

时间:2019-02-27 09:46:29

标签: ruby net-http

我目前有以下代码:

    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)

有没有一种方法可以简化此过程,这样我就不必决定要用于自己的默认端口了?

1 个答案:

答案 0 :(得分:1)

您将使用ruby的动态调度。

$("#collapseOne, #collapseTwo").collapse('hide'); //Close multiple

OR (更优雅的方式):

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)