Dave Dave - 1 year ago 84
Ruby Question

Getting "Error during processing: use_ssl value changed, but session already started" when trying to make https request

I’m using Rails 4.2.7 and this code for making a Net::Http get request

req = Net::HTTP::Get.new(url)
if !headers.nil?
headers.each do |k, v|
req[k] = v
res = Net::HTTP.new(uri.host, uri.port).start do |http|
http.use_ssl = (uri.scheme == "https")
status = res.code
content_type = res['content-type']
content_encoding = res['content-encoding']
content = res.body

However, when I make one in which the scheme is “https”, I get the following error

Error during processing: use_ssl value changed, but session already started
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:758:in `use_ssl='
/Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:118:in `block in get_content'
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:853:in `start'

How do I set https while still being able to make my GET request?

Answer Source

According to docs, use_ssl must be set before starting session.

This is my usual flow:

uri          = URI 'some endpoint with encoded params'
http         = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
headers      = headers.each_with_object({}) { |(k, v), hash| hash[k] = v }
http.get(uri.request_uri, initheader = headers)

See the docs on get.

Sidenote on your

if !headers.nil?

It would be more readable if you just check for presence:

if headers.present?

Or even shorter:

if headers # would return true unless it's nil or false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download