Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal lang how to get binary file from http

In Ruby:

require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')

How to do the same in Crystal?

like image 491
SeventhSon Avatar asked Dec 24 '22 20:12

SeventhSon


2 Answers

We can do the following:

require "http/client"

HTTP::Client.get("http://example.org") do |response|
  File.write("example.com.html", response.body_io)
end

This writes just the response without any HTTP headers to the file. File.write is also smart enough to not download the entire file into memory first, but to write to the file as it reads chunks from the given IO.

like image 76
Jonne Haß Avatar answered Dec 27 '22 07:12

Jonne Haß


I found something that works:

require "http/request"
require "file"
res = HTTP::Client.get "https://ya.ru"
fl=File.open("ya.html","wb")
res.to_io(fl)
fl.close
like image 37
SeventhSon Avatar answered Dec 27 '22 06:12

SeventhSon