Ruby请求https - “in`read_nonblock':连接由peer重置(Errno :: ECONNRESET)”

时间:2013-03-31 05:46:15

标签: ruby ruby-2.0

这是我的代码

domain = 'http://www.google.com'
url = URI.parse "https://graph.facebook.com/fql?q=SELECT%20url,normalized_url%20FROM%20link_stat%20WHERE%20url='#{domain}'"
req = Net::HTTP::Get.new url.path
res = Net::HTTP.start(url.host, url.port) {|http| http.request req}
puts res.body

它给了我

/home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/protocol.rb:153:in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/protocol.rb:153:in `rbuf_fill'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/protocol.rb:134:in `readuntil'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/protocol.rb:144:in `readline'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http/response.rb:39:in `read_status_line'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http/response.rb:28:in `read_new'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:1405:in `block in transport_request'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:1402:in `catch'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:1402:in `transport_request'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:1375:in `request'
    from /home/alex/Documents/ruby_test1.rb:20:in `block in <main>'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:851:in `start'
    from /home/alex/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:582:in `start'
    from /home/alex/Documents/ruby_test1.rb:20:in `<main>'

我做错了什么?

2 个答案:

答案 0 :(得分:22)

您的代码中存在一些奇怪之处。主要是:因为您使用SSL,所以HTTP.start:use_ssl => url.scheme == 'https'有关。HTTP.GetURI构造函数等待domain = 'http://www.google.com' url = URI.parse("https://graph.facebook.com/fql?q=SELECT%20url,normalized_url%20FROM%20link_stat%20WHERE%20url='#{domain}'") req = Net::HTTP::Get.new url res = Net::HTTP.start(url.host, url.port, :use_ssl => url.scheme == 'https') {|http| http.request req} puts res ,而不是路径。总结:

#<Net::HTTPOK:0x000000027d0558>

给出:

{{1}}

答案 1 :(得分:4)

Accepted回答给了我一个错误 -

`initialize': no implicit conversion of Hash into String (TypeError)

当我使用时 -

Net::HTTP.start(url.host, url.port, :use_ssl => url.scheme == 'https')

我的Ruby版本是 -

arup_ruby$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin12.0]

然后,我修改了如下代码: -

require "uri"
require "net/http"

domain = 'http://www.google.com'
uri = URI.parse("https://graph.facebook.com/fql?q=SELECT%20url,normalized_url%20FROM%20link_stat%20WHERE%20url='#{domain}'")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
req = Net::HTTP::Get.new uri
res = http.start { |http| http.request req }
puts res
# >> #<Net::HTTPOK:0x000001018f8520>

它有效。