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

Idiom #102 Load from HTTP GET request into a file

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

extern crate reqwest;
use reqwest::Client;
use std::fs::File;
let client = Client::new();
match client.get(&u).send() {
    Ok(res) => {
        let file = file.create("result.txt")?;
        ::std::io::copy(res, file)?;
    },
    Err(e) => eprintln!("failed to send request: {}", e);
};
import std.net.curl;
u.download("result.txt");
import "fmt"
import "io"
import "net/http"
resp, err := http.Get(u)
if err != nil {
	return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
	return fmt.Errorf("Status: %v", resp.Status)
}
out, err := os.Create("result.txt")
if err != nil {
	return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
	return err
}
1
uses fphttpclient�, classes;
var
  str: TMemorystream;
begin
  with TFPHTTPClient�.create(nil) do 
  try
    str := TMemoryStream.create;
    try
      get(u, str);
      str.saveToFile('result.txt');
    finally
      str.free;
    end;
  finally
    free;
  end;
end;
import urllib
filename, headers = urllib.request.urlretrieve(u, 'result.txt')
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

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms