Ruby:使用open()和NET :: HTTP模块获取Web内容有什么区别? [英] Ruby: what is the difference between using open() and NET::HTTP module to fetch web content?
问题描述
一个单独的SO帖子提供了在Ruby中获取Web内容的不同方法,但没有完全解释为什么一个优于另一个。
A separate SO post offers different methods for fetching web content in Ruby, but doesn't fully explain why one is preferable to the other.
使用open()和NET :: HTTP模块(如下所示)获取Web内容有什么区别?为什么NET :: HTTP被认为是更好的方法?
What is the difference between using open() and the NET::HTTP module, as demonstrated below, to fetch web content? Why is NET::HTTP considered the "better" approach?
**open() 1:**
require 'open-uri'
file = open('http://hiscore.runescape.com/index_lite.ws?player=zezima')
contents = file.read
**open() 2:**
require 'open-uri'
source = open('http://www.google.com', &:read)
**NET::HTTP 1:**
require 'uri'
require 'net/http'
url = "http://hiscore.runescape.com/index_lite.ws?player=zezima"
r = Net::HTTP.get_response(URI.parse(url).host, URI.parse(url).path)
推荐答案
经验法则:使用 OpenURI
。
原因是 OpenURI
只是 Net :: HTTP
,因此需要编写更少的代码。因此,如果你所做的只是执行简单的GET请求,那就去吧。
The reason is that OpenURI
is just a wrapper around Net::HTTP
, therefore it will require less code to be written. So if all you do is performing simple GET requests, go for it.
另一方面,更喜欢 Net :: HTTP
如果你想要一些 OpenURI
没有给你的低级功能。它不是更好的方法,但它在配置方面提供了更多灵活性。
On the other hand, prefer Net::HTTP
if you want some lower-level functionality that you OpenURI
does not give you. It is not a better approach, but it provides more flexibility in terms of configuration.
作为官方文档声明:
如果您只是执行一些GET请求,您应该尝试OpenURI。
这篇关于Ruby:使用open()和NET :: HTTP模块获取Web内容有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!