【问题标题】:Ruby Net::HTTP Get request Error when using httpsRuby Net::HTTP 使用 https 时获取请求错误
【发布时间】:2015-12-07 04:59:48
【问题描述】:

我有一个网络服务器,我需要从中获取一些数据。我想重用连接,所以我选择了HTTP.new

require "net/http"
require "openssl"
uri = URI.parse("https://example.com")
path = "/index.html"
http = Net::HTTP.new(uri.host, uri.port,
    :use_ssl => uri.scheme == 'https')
request = Net::HTTP::Get.new "/index.html"
response = http.request(request)

发出请求时 (response = http.request(request)) ruby​​ 抛出一个TypeError

TypeError: no implicit conversion of Hash into String
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `initialize'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `open'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `block in connect'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/timeout.rb:74:in `timeout'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:878:in `connect'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:863:in `do_start'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:852:in `start'
    from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/net/http.rb:1375:in `request'
    from (irb):14
    from /usr/local/bin/irb:11:in `<main>'

当我使用 http 时,同样的请求有效

【问题讨论】:

  • 对我来说,问题实际上出在Net::HTTP.new(uri.host, uri.port, :use_ssl =&gt; uri.scheme == 'https'),因为这与不接受HashNet::HTTP.new 的签名不匹配。方法签名是new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)。我觉得应该是http = Net::HTTP.new(uri.host, uri.port); http.use_ssl = uri.scheme == 'https';

标签: ruby https get net-http


【解决方案1】:

我不确定您没有使调用过于复杂。为什么不直接使用:

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

我假设您已经知道您的目标服务器是否需要 HTTPS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多