Sample code for 30+ languages & platforms
Rust

REST Read Binary Response into BinData Object (Amazon S3)

Demonstrates how to make a REST call that returns a binary response body. This example is valid for files that fit in memory. The example shows how to download a JPG from the Amazon S3 service.

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

// Connect to the Amazon AWS REST server.
let b_tls = true;
let port = 443;
let b_auto_reconnect = true;
let _ = rest.connect("s3.amazonaws.com", port, b_tls, b_auto_reconnect).is_ok();

// ----------------------------------------------------------------------------
// Important: For buckets created in regions outside us-east-1,
// there are three important changes that need to be made.
// See Working with S3 Buckets in Non-us-east-1 Regions for the details.
// ----------------------------------------------------------------------------

// Provide AWS credentials for the REST call.
let auth_aws = chilkat::AuthAws::new();
auth_aws.set_access_key("AWS_ACCESS_KEY");
auth_aws.set_secret_key("AWS_SECRET_KEY");
auth_aws.set_service_name("s3");
let _ = rest.set_auth_aws(&auth_aws).is_ok();

// Set the bucket name via the HOST header.
// In this case, the bucket name is "chilkat100".
rest.set_host("chilkat100.s3.amazonaws.com");

// Send the request to download the JPG.
if rest.send_req_no_body("GET", "/starfish.jpg").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 JPG 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 err_response = rest.read_resp_body_string().unwrap_or_default();
    if !rest.last_method_success() {
        println!("{}", rest.last_error_text());
    } else {
        println!("{}", err_response);
    }

    return;
}

let bd_body = chilkat::BinData::new();
if rest.read_resp_bd(&bd_body).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

// Save the contents of the response body to a file.
if bd_body.write_file("qa_output/starfish.jpg").is_ok() {
    println!("Success");
} else {
    println!("Failed to write file.");
}