ruby net / http:如何在HTTPS POST请求上修复EOFError

yuntan_t

我正在编写一个脚本来从GitHub v4 API获取数据。但是我的Ruby脚本失败了EOFError如何避免EOFError

以下代码在失败end of file reached (EOFError)我运行了10次脚本,但没有人成功。

require 'net/http'
require 'uri'

uri = URI.parse 'https://api.github.com/graphql'
header = {
  'Authorization' => 'bearer MY_GITHUB_TOKEN',
}

Net::HTTP.new uri.host, uri.port do |http|
  http.use_ssl = true
end.start do |http|
  req = Net::HTTP::Post.new uri.path, header
  req.body = " \
 { \
   \"query\": \"query { viewer { login }}\" \
 } \
"
  http.request req do |res|
    p res.code
    p res.message
    p res.body
    p res.read_body
    res.read_body do |body|
      p body
    end
  end
end

我正在使用ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux] 由rbenv-build编译的Ruby 我得到了堆栈跟踪。

Traceback (most recent call last):
        11: from tmp.rb:20:in `<main>'
        10: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http.rb:920:in `start'
         9: from tmp.rb:31:in `block in <main>'
         8: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http.rb:1479:in `request'
         7: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http.rb:1506:in `transport_request'
         6: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http.rb:1506:in `catch'
         5: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http.rb:1509:in `block in transport_request'
         4: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http/response.rb:29:in `read_new'
         3: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/http/response.rb:40:in `read_status_line'
         2: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/protocol.rb:201:in `readline'
         1: from /home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/protocol.rb:191:in `readuntil'
/home/yuntan/.rbenv/versions/2.6.3/lib/ruby/2.6.0/net/protocol.rb:225:in `rbuf_fill': end of file reached (EOFError)
yuntan_t

由于我的错误猜测。

Net::HTTP.new 不占用任何块,因此下面的代码

Net::HTTP.new uri.host, uri.port do |http|
  http.use_ssl = true
end.start ...

应该

(Net::HTTP.new uri.host, uri.port).tap do |http|
  http.use_ssl = true
end.start ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章