Ruby发出Web请求

时间:2013-12-18 05:22:08

标签: ruby http httpwebrequest

嗨,这是我的第一个Ruby程序。 我正在尝试编写一个简单的ruby应用程序来请求URL并查看它是否可用。如果是,它将打印正常,否则它将打印错误。

这是我到目前为止,你可以请求协助,我需要导入任何库吗?

class WebRequest

    def initialize(name)
        @name = name.capitalize
    end
    def makeRequest
        puts "Hello #{@name}!"

        @uri = URI.parse("https://example.com/some/path")
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE # read into this
        @data = http.get(uri.request_uri)

    end

end

req = WebRequest.new("Archie")
req.makeRequest

4 个答案:

答案 0 :(得分:2)

以下是执行任何请求的示例代码:

require 'net/http'
require 'uri'

url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) do |http|
  http.request(req)
end
puts res.body

答案 1 :(得分:1)

    gem install httparty

然后

    require 'httparty'
    response = HTTParty.get('https://example.com/some/pathm')
    puts response.body

答案 2 :(得分:0)

更简单:

    [1] pry(main)> require 'open-uri'
    => true
    [2] pry(main)> payload = open('http://www.google.com')
    => #<File:/var/folders/2p/24pztc5s63d69hhx81002bq80000gn/T/open-uri20131217-84948-ttwnho>
    [3] pry(main)> payload.inspect
    => "#<Tempfile:/var/folders/2p/24pztc5s63d69hhx81002bq80000gn/T/open-uri20131217-84948-ttwnho>"
    [4] pry(main)> payload.read

payload.read将返回响应正文,您可以轻松地将有效负载用作File对象,因为它是Tempfile的实例

答案 3 :(得分:0)

这就是我最终的结果

require 'net/http'

class WebRequest

    def initialize()
        @url_addr = 'http://www.google.com/'
    end
    def makeRequest

        puts ""

        begin  
            url = URI.parse(@url_addr)
            req = Net::HTTP::Get.new(url.path)
            res = Net::HTTP.start(url.host, url.port) {|http|
            http.request(req)
            }

            puts "OK Connected to #{@url_addr} with status code #{res.code}"
        rescue
            puts "Failed to connect to #{@url_addr}"
        end
    end
end

req = WebRequest.new()
req.makeRequest