Sample code for 30+ languages & platforms
Rust

HTTP Download to Stream

See more REST Examples

Demonstrates how to stream the response body directly to a stream, which in this case is to a file stream.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let rest = chilkat::Rest::new();

// The URL we want to download is: 
// https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip
let url = chilkat::Url::new();
let _ = url.parse_url("https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip");

// Connect to the web server
let b_auto_reconnect = true;
if rest.connect(&url.host(), url.port(), url.ssl(), b_auto_reconnect).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

if rest.send_req_no_body("GET", &url.path()).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

// Read the response header.
let response_status_code = rest.read_response_header();
if response_status_code < 0 {
    println!("{}", rest.last_error_text());
    return;
}

println!("Response status code = {}", response_status_code);

// We expect a 200 response status if the file data is coming.
// Otherwise, we'll get a string response body with an error message(or no response body).
if response_status_code == 200 {

    let body_stream = chilkat::Stream::new();

    // The stream's sink will be a file.
    body_stream.set_sink_file("qa_output/OAuth2-CSharp-Desktop/archive/master.zip");

    // Read the response body to the stream.  Given that we've
    // set the stream's sink to a file, it will stream directly
    // to the file.
    if rest.read_resp_body_stream(&body_stream, true).is_err() {
        println!("{}", rest.last_error_text());
        return;
    }

    println!("Successfully downloaded the file.");

} else {
    let err_response = rest.read_resp_body_string().unwrap_or_default();
    if !rest.last_method_success() {
        println!("{}", rest.last_error_text());
    } else {
        println!("{}", err_response);
    }

}