如何使用 Ruby on Rails 发出 HTTP 请求? [英] How to make a HTTP request using Ruby on Rails?

查看:42
本文介绍了如何使用 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

这篇关于如何使用 Ruby on Rails 发出 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆