Crystal语言:如何从HTTP获取二进制文件?

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

如何在Crystal中执行相同操作?

这个社区的开端并不是那么轻松就能完成的。 - ckruczek
我花了足够的时间在谷歌上搜索,但没有结果。 - SeventhSon
https://crystal-lang.org/api/0.21.0/HTTP/WebSocket/Protocol/StreamIO.html 返回404。 - SeventhSon
2个回答

10

我们可以做以下事情:

require "http/client"

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

这只将响应内容写入文件,不带任何HTTP头信息。 File.write 很聪明,不会先将整个文件下载到内存中,而是在读取给定的IO块时直接写入文件。


谢谢John,确实能用,但没有HTTP头。 - SeventhSon

1
我发现了一个有效的东西:

require "http/request"
require "file"
res = HTTP::Client.get "https://ya.ru"
fl=File.open("ya.html","wb")
res.to_io(fl)
fl.close

当然,你应该更喜欢使用 File.open 的块形式。 - Jonne Haß

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接