简体   繁体   中英

How to capture a response from an HTTP GET request

This is what I came up with, but I feel that there's a better way. I've also heard that I shouldn't use open-uri.

require 'open-uri'

min = 1
max = 1000

str = open("http://www.random.org/integers/?num=#{min}&min=1&max=#{max}&col=1&base=10&format=plain&rnd=new").read

puts str.chomp.to_i

It looks like normal way, but if you're interested in another option, take a look at this:

require 'net/http'

min = 1
max = 1000
address = "http://www.random.org/integers/?num=#{min}&min=1&max={#max}&col=1&base=10&format=plain&rnd=new"

url = URI.parse(address)
response = Net::HTTP.get_response(url)
puts response.body  # => 932

Your code is ok, but since you asked, I'd write it a bit differently:

require 'open-uri'

url_template = "http://www.random.org/integers/?num=%{min}&min=1&max=%{max}&col=1&base=10&format=plain&rnd=new"
random_number = open(url_template % {:min => 1, :max => 1000}).readline.to_i
#=> 42

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM