如何使用Vala通过HTTP下载文件?

问题描述 投票:1回答:1

我尝试将libsoup-2.4与https://valadoc.org/libsoup-2.4/Soup.RequestFile.html一起使用

但是创建RequestFile受保护,我看不到任何返回该对象或继承RequestFile的对象的操作。

以下作品,但是我想知道是否有更短或更佳的方法,无论是使用相同的库还是使用其他库。

// Where url is a string containing the file location (https://...)
Soup.Request request = session.request (url);
InputStream stream = request.send ();

// Create the file
File file = File.new_for_path ("Example File.zip");
FileOutputStream os = file.create (FileCreateFlags.REPLACE_DESTINATION);

// Write bytes to the file
os.splice (stream, OutputStreamSpliceFlags.CLOSE_TARGET);
vala libsoup
1个回答
2
投票

是的,使用gio-2.0可以更轻松地完成此操作。只需通过URL打开第一个文件,然后在本地打开第二个文件,然后将第一个文件复制到第二个文件即可。以下示例下载此html页面的代码。

void main () {
    var file_from_http = File.new_for_uri ("https://stackoverflow.com/questions/61021171/how-do-you-download-files-over-http-with-vala");
    File local_file = File.new_for_path("./stackoverflow.html");
    file_from_http.copy(local_file, FileCopyFlags.OVERWRITE);
}
© www.soinside.com 2019 - 2024. All rights reserved.