use_ssl 值已更改,但尝试发出 https 请求时会话已启动
use_ssl value changed, but session already started when trying to make https request
我正在使用 Rails 4.2.7,此代码用于发出 Net::Http get 请求
req = Net::HTTP::Get.new(url)
if !headers.nil?
headers.each do |k, v|
req[k] = v
end
end
res = Net::HTTP.new(uri.host, uri.port).start do |http|
http.use_ssl = (uri.scheme == "https")
http.request(req)
end
status = res.code
content_type = res['content-type']
content_encoding = res['content-encoding']
content = res.body
但是,当我制作一个协议为“https”的程序时,出现以下错误
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'
如何在设置 https 的同时仍然能够发出 GET 请求?
根据文档,use_ssl
必须在开始会话之前设置。
这是我通常的流程:
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)
请参阅 get
上的文档。
你的旁注
if !headers.nil?
如果你只检查是否存在,它会更具可读性:
if headers.present?
或更短:
if headers # would return true unless it's nil or false
我正在使用 Rails 4.2.7,此代码用于发出 Net::Http get 请求
req = Net::HTTP::Get.new(url)
if !headers.nil?
headers.each do |k, v|
req[k] = v
end
end
res = Net::HTTP.new(uri.host, uri.port).start do |http|
http.use_ssl = (uri.scheme == "https")
http.request(req)
end
status = res.code
content_type = res['content-type']
content_encoding = res['content-encoding']
content = res.body
但是,当我制作一个协议为“https”的程序时,出现以下错误
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'
如何在设置 https 的同时仍然能够发出 GET 请求?
根据文档,use_ssl
必须在开始会话之前设置。
这是我通常的流程:
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)
请参阅 get
上的文档。
你的旁注
if !headers.nil?
如果你只检查是否存在,它会更具可读性:
if headers.present?
或更短:
if headers # would return true unless it's nil or false