5

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.

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)
Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • OpenURI is an easy-to-use wrapper for net/http, net/https and net/ftp from the documentation: http://www.ruby-doc.org/stdlib-2.1.0/libdoc/open-uri/rdoc/OpenURI.html – bjhaid Jan 21 '14 at 23:21
  • 1
    Is this of any use? http://stackoverflow.com/questions/16764030/what-is-the-difference-between-rubys-open-uri-and-nethttp-gems – Aluxzi Jan 21 '14 at 23:25
  • Where is 'NET::HTTP considered the "better" approach'?? – mhutter Jan 22 '14 at 10:39
  • comments on the accepted answer indicate that it's better in general: http://stackoverflow.com/questions/1854207/getting-webpage-content-with-ruby-im-having-troubles. is it not? we don't know; hence the question. – Crashalot Jan 23 '14 at 08:23
  • the other SO questions don't explain the differences among the three choices and when one might be preferable over another... – Crashalot Jan 23 '14 at 10:40

1 Answers1

3

Rule of thumb: Use OpenURI whenever you can.

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.

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.

As the official documentation states:

If you are only performing a few GET requests you should try OpenURI.

Agis
  • 32,639
  • 3
  • 73
  • 81