23

How do I download a file over HTTP using Ruby?

Markus
  • 251
  • 1
  • 3
  • 4

5 Answers5

21

Probably the shortest way to download a file:

require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')
Clemens Helm
  • 3,530
  • 1
  • 19
  • 13
  • 1
    Thanks @Clemens, this solution Just Worked. You might consider answering this here, too: https://stackoverflow.com/questions/2263540/how-do-i-download-a-binary-file-over-http – Gabe Kopley Jun 19 '15 at 00:10
12

You can use open-uri, which is a one liner

require 'open-uri'

content = open('http://example.com').read
KrauseFx
  • 11,234
  • 6
  • 45
  • 53
11
require 'net/http'
#part of base library
Net::HTTP.start("your.webhost.com") { |http|
  resp = http.get("/yourfile.xml")
  open("yourfile.xml", "wb") { |file|
    file.write(resp.body)
  }
}
MattMcKnight
  • 8,081
  • 27
  • 34
5

There are several ways, but the easiest is probably OpenURI. This blog post has some sample code, and also goes over Net::HTTP (with Hpricot) and Rio.

Jordan Running
  • 97,653
  • 15
  • 175
  • 173
  • The easiest, and the most dangerous. OpenURI patches Kernel#open, and if any user input ever gets close to the string you're about to open, the door is open for both reading any file on the system and remote code execution. – haslo Jun 14 '18 at 12:41
4

Simple...

response = Net::HTTP.get_response(URI.parse("yourURI"))
JRL
  • 74,629
  • 18
  • 94
  • 144