0

Hi this is my very first Ruby program. I'm trying to write a simple ruby app to make a request to a URL and see if it's available. If it is, it'll print OK and else it'll print false.

This is what I've got so far, can you please assist, do I need to import any libs?

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 Answers 4

2

Here is sample code to do any request:

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
Sign up to request clarification or add additional context in comments.

Comments

1
    gem install httparty

then

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

Comments

0

Something simpler:

    [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 would return the response body and you can easy use payload as File object since it is an instance of Tempfile

Comments

0

This is what I've ended up with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.