如何使用Ruby通过HTTP下载文件?
可能是下载文件的最短路径:
require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')
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)
}
}
您可以使用一行代码的 open-uri。
require 'open-uri'
content = open('http://example.com').read
Simple...
response = Net::HTTP.get_response(URI.parse("yourURI"))
content = URI.parse('http://your_url.com').read
这样的操作更安全。请参阅http://docs.rubocop.org/rubocop/cops_security.html#securityopen”。 - sb813322
URI.open
代替open
。 - Michael