From d92413c2b19cb874e7f9aa6bdae28cc490609523 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Mon, 25 Jul 2011 21:32:26 -0400 Subject: [PATCH] done with 14.1 --- cookbook/014/01.rb | 46 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/cookbook/014/01.rb b/cookbook/014/01.rb index 47fe622..b1fa3bb 100644 --- a/cookbook/014/01.rb +++ b/cookbook/014/01.rb @@ -1,3 +1,45 @@ require 'open-uri' -head = open('http://www.oreilly.com/').read(200) -puts head +puts 'using "open-uri"' +puts open('http://oreilly.com/').read(200) + +# ------------------------------------------------------------ +require 'net/http' +puts 'using "net/http"' +response = Net::HTTP.get_response('oreilly.com', '/about/') +puts 'response.code=', response.code +puts 'response.body.size=', response.body.size +puts 'response[\'Content-type\']=', response['Content-type'] +puts 'response[0, 200]', response.body[0, 200] + + +# ------------------------------------------------------------ +require 'uri' +puts 'using "net/http" with a URI' +puts 'request object:', \ + Net::HTTP.get(URI.parse("http://oreilly.com")) +puts 'full response:' +response = Net::HTTP.get_response(URI.parse("http://oreilly.com/about/")) + +# ......... +puts "Success!" if response.is_a? Net::HTTPOK + +puts case response.code[0] + when ?1 then "Status code indicates an HTTP informational response." + when ?2 then "Status code indicates success." + when ?3 then "Status code indicates redirection." + when ?4 then "Status code indicates client error." + when ?5 then "Status code indicates server error." + else "Non-standard status code." +end + +puts 'Server=', response['Server'] +puts 'SERVER=', response['SERVER'] + +puts 'all keys:' +response.each_key { |key| puts key } + +Net::HTTP.get_response('oreilly.com', '/about/') do |response| + response.read_body do |segment| + puts "Received segment of #{segment.size} byte(s)!" + end +end