How do I download a file over HTTP using Ruby?
Asked
Active
Viewed 2.1k times
5 Answers
25
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,841
- 1
- 22
- 13
-
1Thanks @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
-
3Does not work with more recent versions of ruby. Use `URI.open` instead of `open`. – Michael Sep 28 '22 at 14:30
13
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,185
- 28
- 35
12
You can use open-uri, which is a one liner
require 'open-uri'
content = open('http://example.com').read

KrauseFx
- 11,551
- 7
- 46
- 53
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
- 102,619
- 17
- 182
- 182
-
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
-
You can consider [this comment](https://stackoverflow.com/questions/3647221/ruby-nethttpget-and-json-responses#comment122667651_3647237) for more information. Quoting: "Note unless you can be certain the url cannot have been maliciously crafted (e.g. by user input) something like `content = URI.parse('http://your_url.com').read` is safer. See http://docs.rubocop.org/rubocop/cops_security.html#securityopen " – sb813322 Jan 04 '23 at 13:54