parm530
2/20/2019 - 6:15 PM

Making GET Requests in Ruby

Making Requests in Ruby

  • Using net/http
    • make sure your file: require 'net/http'
    • this will also require 'uri' so you don't need to manually include this
uri = URI('http://www.blahblah.com')
// same as uri = URI.parse('http://www.blahblah.com')

Net::HTTP.start(uri.host, uri.port) do |http|
 request = Net::HTTP.Get.new uri
 
 response = http.request request # Net::HTTPResponse object
end
  • .start creates a connection to an HTTP server and keeps the connection for the duration of the block
  • connection will remain open for any requests within the block as well
  • Post requests are similar, just follow posting request
    • post requests are made outside the start of the connection
  • You can specify the content_type and body params for the URI:
uri = URI("www....")
request = Net::HTTP.Post.new uri.path

// HEADER
request.content_type = "application/json"

// BODY
// dump converts the json to a string
request.body = JSON.dump({
  "arg1" => "val1",
  "arg2" => "val2", 
  ...
})

Enable HTTPS

uri = "www.google.com/sjf"

Net:HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") do |http|

request = Net::HTTP.Get.new uri
resp = http.request request

end