How do you download files over HTTP with Vala?

373 views Asked by At

I attempted to use libsoup-2.4 with https://valadoc.org/libsoup-2.4/Soup.RequestFile.html

but the creation of RequestFile is protected and I can't see any operation that returns that object or an object that inherits RequestFile.

The following works, but I was wondering if there was a shorter or better way, whether it is with the same library or others.

// 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);
1

There are 1 answers

3
gavr On BEST ANSWER

Yes, this can be done more easily with gio-2.0. Just open first file by URL, the second file locally, and copy the first one to the second. The following example downloads the code of this html page.

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);
}