首页 > 解决方案 > 使用 aws-sdk-cpp 构建示例应用程序以从 s3 存储桶下载对象

问题描述

我是新手,最近开始学习 AWS。

我已经下载并编译了 aws-sdk-cpp。我正在尝试使用 aws sdk 文档中提供的 get_object.cpp 示例构建示例应用程序。

但是我的示例给出了 curl 代码 56。我检查了 tcpdump,发现它无法找到正确的主机。我没有使用任何代理。我试过 curl "https://api.dev.abc.com:8080/bucket_name/object_name" 这工作正常。但是我的示例应用程序出现 curl 错误 56。

我附上示例应用程序供您参考。能否请您看一下代码并帮助我解决问题。

示例代码

#include <iostream>
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <fstream>
#include <awsdoc/s3/s3_examples.h>

bool AwsDoc::S3::GetObject(const Aws::String& objectKey,
    const Aws::String& fromBucket, const Aws::String& region)
{
    Aws::Client::ClientConfiguration config;

    //curl https://api.dev.abc.com:8080/bucket_name/object_name
    if (!region.empty())
    {
        config.region = region;
        config.proxyHost = "api.dev.abc.com";
        config.proxyPort = 8080;
        config.proxyScheme = Aws::Http::Scheme::HTTPS;
    }
    Aws::Auth::AWSCredentials cred("xxxxxxx", "yyyyyy");

    Aws::S3::S3Client s3_client(cred, config);

    Aws::S3::Model::GetObjectRequest object_request;
    object_request.SetBucket(fromBucket);
    object_request.SetKey(objectKey);

    Aws::S3::Model::GetObjectOutcome get_object_outcome = 
        s3_client.GetObject(object_request);

    if (get_object_outcome.IsSuccess())
    {
        auto& retrieved_file = get_object_outcome.GetResultWithOwnership().
            GetBody();

        // Print a beginning portion of the text file.
        std::cout << "Beginning of file contents:\n";
        char file_data[255] = { 0 };
        retrieved_file.getline(file_data, 254);
        std::cout << file_data << std::endl;

        return true;
    }
    else
    {
        auto err = get_object_outcome.GetError();
        std::cout << "Error: GetObject: " <<
            err.GetExceptionName() << ": " << err.GetMessage() << std::endl;

        return false;
    }
}

int main()
{
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        //TODO: Change bucket_name to the name of a bucket in your account.
        const Aws::String bucket_name = "bucket_name";
        //TODO: The bucket "DOC-EXAMPLE-BUCKET" must have been created and previously loaded with "my-file.txt". 
        //See create_bucket.cpp and put_object.cpp to create a bucket and load an object into that bucket.
        const Aws::String object_name = "object_name";
        //TODO: Set to the AWS Region in which the bucket was created.
        const Aws::String region = "India_South";

        if (!AwsDoc::S3::GetObject(object_name, bucket_name, region))
        {
            return 1;
        }
    }
    Aws::ShutdownAPI(options);

    return 0;
}

标签: amazon-s3aws-sdk-cpp

解决方案


推荐阅读