Sample code for 30+ languages & platforms
Rust

(using AWS Signature Version 2) Streaming Download to File

See more Amazon S3 (new) Examples

The main purpose of this example is to demonstrate how to use the older Signature Version 2 authentication w/ S3. It uses V2 authentication to download 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();

// Connect to the Amazon AWS REST server.
let b_tls = true;
let port = 443;
let b_auto_reconnect = true;
// The file is located in the bucket named "chilkat100", which becomes part of the domain:
let _ = rest.connect("chilkat100.s3.amazonaws.com", port, b_tls, b_auto_reconnect).is_ok();

// 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");

// For AWS Signature Version 2, the following two properties need to be set:
auth_aws.set_signature_version(2);
// See http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#ConstructingTheCanonicalizedResourceElement
auth_aws.set_canonicalized_resource_v2("/chilkat100/starfish.jpg");

let _ = rest.set_auth_aws(&auth_aws).is_ok();

// 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 body_stream = chilkat::Stream::new();

    // The stream's sink will be a file.
    body_stream.set_sink_file("qa_output/starfish.jpg");

    // 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 received the JPG 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);
    }

}