1

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);
g_l
  • 621
  • 5
  • 15

1 Answers1

2

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);
}
gavr
  • 807
  • 7
  • 16
  • Does this work on Windows as well? I think GIO uses GVfs for its HTTP back end and I'm not sure how well that works on other platforms – AlThomas Apr 04 '20 at 13:20
  • GIO is cross-platform. This is also confirmed by the fact that we have gio-unix and gio-windows I think. https://imgur.com/gallery/54i6ew1 – gavr Apr 05 '20 at 01:37
  • Yes, GIO is a high level, cross-platform, API. It works well with files and sockets, but other protocols require different back ends. GIO uses [GVfs](https://wiki.gnome.org/Projects/gvfs) for a [number of schemes](https://wiki.gnome.org/Projects/gvfs/schemes) and they each use their own [back ends](https://wiki.gnome.org/Projects/gvfs/backends). It's good to know that the HTTP back end (using GVfs and libsoup) works in a pure Windows environment, thanks – AlThomas Apr 05 '20 at 11:34