如何使用 Ruby on Rails 发出 HTTP 请求?
我想从另一个网站获取信息。因此(也许)我应该向该网站发出请求(在我的例子中是 HTTP GET 请求)并接收响应。
我怎样才能在 Ruby on Rails 中做到这一点?
如果可能的话,在我的控制器中使用它是否是正确的方法?
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.
How can I make this in Ruby on Rails?
If it is possible, is it a correct approach to use in my controllers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 Ruby 的
Net::HTTP< /code>
类:
You can use Ruby's
Net::HTTP
class:Net::HTTP 内置于 Ruby 中,但让我们面对现实吧,通常使用其繁琐的 1980 年代风格并尝试更高级别的替代方案会更容易:
Net::HTTP is built into Ruby, but let's face it, often it's easier not to use its cumbersome 1980s style and try a higher level alternative:
OpenURI 是最好的;就这么简单
OpenURI is the best; it's as simple as
我更喜欢 httpclient 而不是 Net::HTTP。
如果您要创建一个作为服务客户端的类,那么 HTTParty 是一个不错的选择。这是一个方便的 mixin,可以满足您 90% 的需求。在示例中了解 Google 和 Twitter 客户端有多短。
回答你的第二个问题:不,我不会把这个功能放在控制器中——如果可能的话,我会使用模型来封装细节(也许使用 HTTParty),然后简单地从控制器调用它。
I prefer httpclient over Net::HTTP.
HTTParty is a good choice if you're making a class that's a client for a service. It's a convenient mixin that gives you 90% of what you need. See how short the Google and Twitter clients are in the examples.
And to answer your second question: no, I wouldn't put this functionality in a controller--I'd use a model instead if possible to encapsulate the particulars (perhaps using HTTParty) and simply call it from the controller.
如果您在代理后面进行 REST api 调用,则以下代码有效:
Here is the code that works if you are making a REST api call behind a proxy:
我最喜欢的两种获取 URL 内容的方法是 OpenURI 或 Typhoeus。
OpenURI 因为它无处不在,而 Typhoeus 因为它非常灵活和强大。
My favorite two ways to grab the contents of URLs are either OpenURI or Typhoeus.
OpenURI because it's everywhere, and Typhoeus because it's very flexible and powerful.