我正在使用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'
如何在仍然能够发出GET请求的同时设置https?
答案 0 :(得分:0)
根据文档,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