Created
April 26, 2012 09:03
-
-
Save lfborjas/2497882 to your computer and use it in GitHub Desktop.
Usando Net::HTTP para consumir httparty.herokuapp.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
require 'json' | |
def get(url, opts) | |
opts ||= {} | |
uri = URI(url) | |
req = Net::HTTP::Get.new(uri.request_uri) | |
if opts[:headers] | |
opts[:headers].each do |header, value| | |
req[header] = value | |
end | |
end | |
Net::HTTP.start(uri.hostname, uri.port){|http| http.request(req) } | |
end | |
def parse_json(res) | |
JSON.parse(res.body) | |
end | |
host = "http://httparty.herokuapp.com" | |
#1. Obtener las ids | |
list_res = get("#{host}/quotes", headers: {'Accept' => "application/json"}) | |
ids = parse_json(list_res).map{|quote| quote["id"] } | |
#2. Elegir tres al azar | |
sample = ids.sample(3) | |
puts "I've chosen: #{sample.inspect}" | |
cookie = "" | |
sample.each do |quote_id| | |
quote_res = get("#{host}/quotes/#{quote_id}", headers: {'Accept' => "application/json", 'Cookie' => cookie}) | |
cookie = quote_res['Set-Cookie'] | |
end | |
#Obtener las leídas | |
# | |
puts "Quotes I've read:" | |
res = get("#{host}/quotes/read", headers: {'Accept' => 'text/plain', 'Cookie' => cookie}) | |
puts res.body | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment