HTTPS request using Net::HTTP's block form -- is it possible?

John Bachir picture John Bachir · Jun 14, 2011 · Viewed 8.2k times · Source

To do a Net::HTTP https request without the block form you can do this:

...
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
...

But is there a way to tell Net::HTTP to use https when doing the block form?

u = URI.parse(url)
Net::HTTP.start(u.host, u.port) do |http|
  # if I put http.use_ssl = true here, ruby complains that this can't
  # be done becuase the sesion has already started
  resp = http.get(u.request_uri)
end

I'm on ruby 1.8.7

Answer

Lee Jarvis picture Lee Jarvis · Jun 14, 2011

See the documentation for Net::HTTP.start which takes an optional hash. From the documentation:

opt sets following values by its accessor. The keys are ca_file, ca_path, cert, cert_store, ciphers, close_on_empty_response, key, open_timeout, read_timeout, ssl_timeout, ssl_version, use_ssl, verify_callback, verify_depth and verify_mode. If you set :use_ssl as true, you can use https and default value of verify_mode is set as OpenSSL::SSL::VERIFY_PEER.

Net::HTTP.start(url.host, url.port, :use_ssl => true)