【问题标题】:How to send a request to localhost using 'net/http' fails with end of file reached (EOFError)如何使用“net/http”向 localhost 发送请求失败并到达文件末尾(EOFError)
【发布时间】:2016-11-21 12:59:03
【问题描述】:

我使用的是 Ruby 2.3.0 版。

我想检查我的应用程序何时启动,我为我的“部署者”编写了这个方法。 在运行时http.request_get(uri) 引发

EOFError: end of file reached

当我将http://localhost 作为第一个参数传递给方法时:

require 'net/http'

def check_start_application(address, port)
  success_codes = [200, 301]
  attempts = 200
  uri = URI.parse("#{address}:#{port}")
  http = Net::HTTP.new(uri.host, uri.port)

  attempts.times do |attempt|
    # it raises EOFError: end of file reached
    http.request_get(uri) do |response|
      if success_codes.include?(response.code.to_i)
        return true
      elsif attempt == attempts - 1
        return false
      end
    end
  end
end

但是,当我使用 irb 与上下文分开测试此方法时,此代码适用于两种情况:

check_start_application('http://example.com', '80')
check_start_application('http://localhost', any_port)

在应用程序的上下文中,此代码仅适用于一种情况:

check_start_application('http://example.com', '80')

我尝试了什么:

  • 使用“rest-client”而不是“net/http”
  • 使用“net/https”和http.use_ssl = false
  • 从方法中删除times
  • 在请求之前致电sleep

谁遇到过类似的问题?我相信我不是唯一一个。

【问题讨论】:

  • 您的代码在哪个端口上失败了?您的应用是否在 https 上运行?
  • @rorra 谢谢。我的应用程序部署在一个随机的免费端口上,为此我使用 Docker。端口范围在临时端口范围内。该应用未在 https 上运行。
  • @rorra 我通过 %x(curl --write-out %{http_code} --silent 127.0.0.1:#{any_port}) 得到了我想要的。但这不是检查响应的正确方法。

标签: ruby net-http


【解决方案1】:

在部署时,您的应用可能在 SSL 上运行。如果没有访问权限,很难帮助调试,但请尝试:

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

【讨论】:

    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2017-12-29
    • 2013-05-25
    相关资源
    最近更新 更多