Created
April 26, 2012 18:06
-
-
Save lfborjas/2501497 to your computer and use it in GitHub Desktop.
El ejemplo de Net::HTTP
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 'uri' | |
require 'net/http' | |
require 'json' | |
host = "http://httparty.herokuapp.com" | |
#let's store the cookie here | |
cookie = "" | |
#let's read some quotes | |
3.times do |quote_id| | |
quote_uri = URI("#{host}/quotes/random") | |
quote_req = Net::HTTP::Get.new(quote_uri.request_uri) | |
quote_req['Accept'] = "application/json" | |
#if we have a cookie, use it | |
quote_req['Cookie'] = cookie unless cookie.empty? | |
quote_res = Net::HTTP.start(quote_uri.hostname, quote_uri.port){|http| http.request(quote_req) } | |
#update the cookie | |
cookie = quote_res['Set-Cookie'] | |
body_hash = JSON.parse(quote_res.body) | |
puts "Reading '#{body_hash["content"]}' by #{body_hash["author"]}" | |
end | |
puts "Quotes I've read:" | |
read_uri = URI("#{host}/quotes/read") | |
read_req = Net::HTTP::Get.new(read_uri.request_uri) | |
read_req['Accept'] = "text/plain" | |
read_req['Cookie'] = cookie | |
read_res = Net::HTTP.start(read_uri.hostname, read_uri.port){|http| http.request(read_req) } | |
puts read_res.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment