Sample code for 30+ languages & platforms
Rust

HTTP POST and Stream Response to File

See more REST Examples

Demonstrates how to send an HTTP POST and stream the response body directly to a file.

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

let url = chilkat::Url::new();
// This URL will emit a response that echos the query params (name and age)
let _ = url.parse_url("https://www.chilkatsoft.com/readPost.asp");

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

let _ = rest.add_query_param("name", "John");
let _ = rest.add_query_param("age", "33");

//  Send the HTTP POST.
if rest.send_req_form_url_encoded("POST", &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/out.txt");

    // 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 streamed the response to a 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);
    }

}