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

查看:206
本文介绍了如何使用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天全站免登陆