Menu

Toshimaru's Blog

Get HTML/JSON response from URL simply in Ruby

GET HTML response from URL

To GET URL and the response simply in Ruby:

require 'net/http'
require 'uri'

uri = URI('https://google.com/')
response = Net::HTTP.get(uri)
  1. Parse URL from URI string
  2. Net::HTTP.get the parsed URL

GET HTTP status code from URL

require 'net/http'
require 'uri'

uri = URI('https://google.com/')
Net::HTTP.get_response(uri).code

get_response method returns Net::HTTPResponse which has methods like code, body, etc.

GET JSON response from URL

require 'net/http'
require 'uri'
require 'json'

uri = URI('http://www.example.com/sample.json')
json = Net::HTTP.get(uri)
result = JSON(json)

Reference

Load more