Monday, March 08, 2010

Dummy version of Http Client in Ruby

RubyCook book's Real-World HTTP Client looks relative complex for me, so i would like to re-organize some code to make it work to send simple requests.

require 'net/http'
require 'uri'

def Http_fetch(uri_str,action='get',data ='',limit = 10)

url = URI.parse("#{uri_str}")

#Get method
if limit ==10 && action == 'get'
res = Net::HTTP.start(url.host, url.port) {|http2|
http2.get(url.path)
}
puts "Get : " + res.code
end

#Post method
if limit ==10 && action == 'post'

http = Net::HTTP.new(url.host, url.port)
res = http.post(url.path, data)
raise "POST FAILED:"+res.inspect unless res.is_a? Net::HTTPOK
puts "Post : " + res.code
return res

end

#Redirects
if limit <10 && limit >0
res = Net::HTTP.get_response(URI.parse(uri_str))
puts "Redirect : " + res.code
end

raise ArgumentError, 'HTTP redirect too deep' if limit == 0

case res

when Net::HTTPSuccess
return res

when Net::HTTPRedirection
puts res['location']
fetch(res['location'], '', '',limit - 1)

else
res.error!
end

end



data_post = "username=***@gmail.com&password=***&language=en"
# Testing Get method
res1 = Http_fetch('http://www.infoq.com/')

# Testing Post method--login to infoq.com
res2 = Http_fetch('http://www.infoq.com/login.action','post',data_post)

# Testing Redirects--this leads me redirect to http://www.ruby-lang.org/en/
res3 = Http_fetch('http://www.ruby-lang.org/')

If you are using Mac OS or Linux, this post can be more helpful: http://fiatdev.com/2009/07/22/patron-0-4

No comments:

Post a Comment