Ruby/Network/HTTP Post
Материал из Wiki.crossplatform.ru
Содержание |
Check web request status code
require "net/http" # The library we need host = "www.example.ru" # The web server path = "/index.html" # The file we want http = Net::HTTP.new(host) # Create a connection headers, body = http.get(path) # Request the file if headers.code == "200" # Check the status code # NOTE: code is not a number! print body # Print body if we got it else # Otherwise puts "#{headers.code} #{headers.message}" # Display error message end
Get random number from random.org
class RandomOrg require "net/http" require "thread" def initialize(min=0,max=1,buff=1000,slack=300) @site = "www.random.org" @min, @max = min, max @bufsize, @slack = buff, slack @buffer = Queue.new @url = "/cgi-bin/randnum?num=nnn&min=#@min&max=#@max&col=1" @thread = Thread.new { fillbuffer } end def fillbuffer h = Net::HTTP.new(@site, 80) true_url = @url.sub(/nnn/,"#{@bufsize-@slack}") resp, data = h.get(true_url, nil) data.split.each {|x| @buffer.enq x } end def rand if @buffer.size < @slack if ! @thread.alive? @thread = Thread.new { fillbuffer } end end num = nil num = @buffer.deq until num!=nil num.to_i end end t = RandomOrg.new(1,6,1000,300) count = {1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0} 10000.times do |n| x = t.rand count[x] += 1 end p count
Net::HTTP:
require "net/http" home = Net::HTTP.new("www.ruby-lang.org", 80) response, text = home.get("/en/index.html", nil) puts text
Posting Form Data
require "net/http" url = URI.parse("http://www.rubyinside.ru/test.cgi") response = Net::HTTP.post_form(url,{"name" => "David", "age" => "24"}) puts response.body
Set form data
require "net/http" url = URI.parse("http://www.rubyinside.ru/test.cgi") Net::HTTP.start(url.host, url.port) do |http| req = Net::HTTP::Post.new(url.path) req.set_form_data({ "name" => "David", "age" => "24" }) puts http.request(req).body end