如何使用 Ruby on Rails 发出 HTTP 请求?
问题描述:
我想从另一个网站获取信息.因此(也许)我应该向该网站发出请求(在我的情况下是 HTTP GET 请求)并接收响应.
I would like to take information from another website. Therefore (maybe) I should make a request to that website (in my case a HTTP GET request) and receive the response.
我怎样才能在 Ruby on Rails 中做到这一点?
How can I make this in Ruby on Rails?
如果可能,它是否是在我的控制器中使用的正确方法?
If it is possible, is it a correct approach to use in my controllers?
答
你可以使用 Ruby 的 Net::HTTP
类:
You can use Ruby's Net::HTTP
class:
require 'net/http'
url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body