Sample code for 30+ languages & platforms
Rust

Stream a REST Response Body to a Destination

See more REST Examples

Demonstrates Rest.SetResponseBodyStream, which configures a Stream destination for response bodies received by the full-request convenience methods. The body is written to the stream only when the response status code matches the expected status.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. Directing the response body to a stream avoids holding a large response in memory. The expected-status argument ensures error responses (which typically have small bodies) are not written to the stream destination.

Chilkat Rust Downloads

Rust

let rest = chilkat::Rest::new();
let b_tls = true;
let b_auto_reconnect = true;
if rest.connect("example.com", 443, b_tls, b_auto_reconnect).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

// The file paths are relative to the application's current working directory.  Absolute paths
// may also be used.  Supply the paths appropriate to your own environment.

// Configure a Stream destination for response bodies received by the full-request convenience
// methods.  The body is written to the stream only when the response status code matches the 1st
// argument.
let resp_stream = chilkat::Stream::new();
resp_stream.set_sink_file("qa_output/response_body.dat");

// The 2nd argument sets the stream character set from the response Content-Type charset for textual
// responses.  The 3rd argument is the destination Stream.
let b_auto_set_charset = true;
let expected_status = 200;
if rest.set_response_body_stream(expected_status, b_auto_set_charset, &resp_stream).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

// The full-request call now streams the response body to the sink instead of returning it.
let Ok(response_text) = rest.full_request_no_body("GET", "/api/largefile") else {
    println!("{}", rest.last_error_text());
    return;
};

println!("Response streamed to file.  Status: {}", rest.response_status_code());