Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Ruby

Idiom #102 Load from HTTP GET request into a file

Make an HTTP request with method GET to the URL u, then store the body of the response in the file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.

require 'net/http'
u = URI('http://example.com/large_file')

Net::HTTP.start(u.host, u.port) do |http|
  request = Net::HTTP::Get.new(u)
  http.request(request) do |response|
    open('result.txt', 'w') do |file|
      response.read_body do |chunk|
        file.write(chunk)
      end
    end
  end
end

The body is passed to the block, provided in fragments, as it is read in from the socket.
require 'open-uri'
response = URI.open(u).read
File.write("result.txt", response)
import std.net.curl;
download(u, "result.txt");

New implementation...
< >
programming-idioms.org