Use the OSS C++ SDK V2 to upload, download, and manage objects in Alibaba Cloud OSS from C++ applications. Built for high-performance scenarios, embedded systems, and desktop applications.
The OSS C++ SDK V2 is in preview. Interfaces may change. Check the GitHub repository release notes for updates.
Quick start
Complete the following steps to install the SDK, configure credentials, and initialize a client.
Prerequisites
-
A C++17 or later compiler (GCC 7+, Clang 5+, or MSVC 2017+).
-
CMake 3.15 or later.
Run the cmake --version command to check your CMake version. If CMake is not installed or the version is earlier than 3.15, download and install CMake.
Install SDK
vcpkg is the recommended installation method.
vcpkg
Use the vcpkg package manager to install the SDK:
vcpkg install alibabacloud-oss-cpp-sdk-v2[curl]
# On Windows, you can use WinHTTP as the HTTP transport layer instead.
vcpkg install alibabacloud-oss-cpp-sdk-v2[winhttp]
You can also install from source code by using an overlay port:
git clone https://github.com/aliyun/alibabacloud-oss-cpp-sdk-v2.git
vcpkg install alibabacloud-oss-cpp-sdk-v2[curl] --overlay-ports=alibabacloud-oss-cpp-sdk-v2/vcpkg --head
You must specify an HTTP transport layer (curl or winhttp), as none is enabled by default. You can enable both.
If both openssl and mbedtls are enabled, openssl takes precedence.
Optional features:
|
Feature |
Description |
|
|
An HTTP transport layer based on libcurl. You must explicitly specify |
|
|
An HTTP transport layer based on WinHTTP (Windows only). |
|
|
Uses OpenSSL for hash calculation. |
|
|
Uses mbedTLS for hash calculation. |
|
|
Enables client-side encryption. On non-Windows platforms, you must also enable |
|
|
Enables runtime type information (RTTI) at compile time. |
Complete definitions: vcpkg/vcpkg.json.
Source code
Download the latest version of the OSS C++ SDK V2 from GitHub, then build and install it with CMake:
git clone https://github.com/aliyun/alibabacloud-oss-cpp-sdk-v2.git
cd alibabacloud-oss-cpp-sdk-v2
mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local
cmake --build . --target install
Available CMake options:
|
Option |
Description |
|
|
Builds the SDK as a shared library. By default, a static library is built (OFF). |
|
|
Uses libcurl as the HTTP transport layer. |
|
|
Uses WinHTTP as the HTTP transport layer (Windows only). |
|
|
Uses the system-installed libcurl instead of the version included with the SDK. |
|
|
Uses the system-installed OpenSSL. |
|
|
Uses the system-installed mbedTLS. |
|
|
Uses |
|
|
Enables client-side encryption. |
|
|
Enables runtime type information (RTTI). |
Add the dependency to your project's CMakeLists.txt file:
cmake_minimum_required(VERSION 3.15)
project(my-app)
find_package(alibabacloud_oss_v2 REQUIRED)
add_executable(MyApp main.cpp)
target_link_libraries(MyApp PRIVATE alibabacloud_oss_v2::oss)
Configure access credentials
Set environment variables with your RAM user's AccessKey pair.
In the RAM console, create a RAM user and generate a permanent AccessKey. Save the AccessKey, and then grant the AliyunOSSFullAccess permission to the user.
Linux
-
In the command-line interface, run the following commands to add the environment variables to your
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Run the following command to apply the changes.
source ~/.bashrc -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
In the terminal, run the following command to check your default shell.
echo $SHELL-
The following steps depend on your default shell.
Zsh
-
Run the following commands to add the environment variables to your
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the changes.
source ~/.zshrc -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the environment variables to your
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the changes.
source ~/.bash_profile -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
Command Prompt
-
In Command Prompt (CMD), run the following commands:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Reopen Command Prompt and run the following commands to verify that the environment variables are set.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
In PowerShell, run the following commands.
[System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User) [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User) -
Reopen PowerShell and run the following commands to verify that the environment variables are set.
[System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User) [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)
Initialize client
The SDK supports three request modes: OSSClient (synchronous), OSSClient (asynchronous) (thread-pool-based), and OSSAsyncClient (asynchronous) (native async). The following examples use ListBuckets to demonstrate each mode.
OSSClient (synchronous)
Use the OSSClient synchronous mode when you need to wait for an operation to complete before proceeding.
Before you run the sample code, replace<region-id>with an actual region and endpoint, such asap-southeast-1.
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
oss::OSSClient client(conf);
auto outcome = client.listBuckets(
oss::models::ListBucketsRequest());
if (!outcome.has_value()) {
auto& err = outcome.error();
std::cerr << "Error Code: " << err.getCode() << std::endl;
std::cerr << "Error Message: " << err.getMessage() << std::endl;
std::cerr << "Request ID: " << err.getRequestId() << std::endl;
return 1;
}
auto& result = outcome.value();
for (auto& bucket : result.getBuckets()) {
std::cout << "bucket: name:" << bucket.name
<< ", region:" << bucket.region
<< ", storageClass:" << bucket.storageClass
<< std::endl;
}
return 0;
}
OSSClient (asynchronous)
This thread-pool-based asynchronous mode still uses OSSClient. After setting conf.executor (a thread pool), you call asyncCall() to dispatch a synchronous request to the thread pool for concurrent execution. The call returns a std::future, and the caller waits for the result with get().
Ifconf.executoris not set,asyncCall()returns aNoExecutorerror.
#include <future>
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
#include "alibabacloud/oss2/utils/DefaultExecutor.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Key: Configure a thread pool to enable asyncCall() support for OSSClient.
conf.executor = std::make_shared<oss::DefaultExecutor>();
oss::OSSClient client(conf);
// Asynchronous call that returns a std::future.
auto future = client.asyncCall(oss::models::ListBucketsRequest());
// Wait for the result by using get() (future pattern).
auto outcome = future.get();
if (!outcome.has_value()) {
auto& err = outcome.error();
std::cerr << "Error Code: " << err.getCode() << std::endl;
std::cerr << "Error Message: " << err.getMessage() << std::endl;
return 1;
}
auto& result = outcome.value();
for (auto& bucket : result.getBuckets()) {
std::cout << "bucket: name:" << bucket.name
<< ", region:" << bucket.region << std::endl;
}
return 0;
}
Concurrent upload and download examples: AsyncCallOnSyncClient.cpp and AsyncCallbackOnSyncClient.cpp.
OSSAsyncClient (asynchronous)
This native asynchronous mode uses OSSAsyncClient. Each operation has a corresponding operationNameAsync() method that receives the result through a callback, eliminating the need to configure a thread pool. This mode is ideal for scenarios that require a high volume of concurrent operations.
Before you run the sample code, replace<region-id>with an actual region and endpoint, such asap-southeast-1.
#include <iostream>
#include <thread>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSAsyncClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
auto client = std::make_shared<oss::OSSAsyncClient>(conf);
client->listBucketsAsync(
oss::models::ListBucketsRequest(),
oss::ListBucketsAsyncCallback([](oss::ListBucketsOutcome outcome) {
if (!outcome.has_value()) {
auto& err = outcome.error();
std::cerr << "Error Code: " << err.getCode() << std::endl;
std::cerr << "Error Message: " << err.getMessage() << std::endl;
return;
}
auto& result = outcome.value();
for (auto& bucket : result.getBuckets()) {
std::cout << "bucket: name:" << bucket.name
<< ", region:" << bucket.region
<< ", storageClass:" << bucket.storageClass
<< std::endl;
}
}));
// Wait for the asynchronous operation to complete.
std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;
}
The output lists all buckets in your account across all regions.
Client configuration
Use a custom domain
A custom domain enables browser-based file preview and CDN-accelerated delivery.
Before you run the sample code, replace<region-id>with an actual region ID from the region and endpoint list, such asap-southeast-1.
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.endpoint = "https://your-custom-domain.com";
conf.useCName = true;
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
oss::OSSClient client(conf);
// Perform operations using the custom domain.
auto outcome = client.putObject(
oss::models::PutObjectRequest()
.setBucket("your-bucket")
.setKey("your-key")
.setBody(oss::RequestBody::fromString("Hello, OSS!")));
if (!outcome.has_value()) {
auto& err = outcome.error();
std::cerr << "Error: " << err.getMessage() << std::endl;
return 1;
}
std::cout << "Upload successful" << std::endl;
return 0;
}
Timeout control
Use connectTimeout and readWriteTimeout to configure the connection and read/write timeouts in milliseconds.
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Set the connection timeout to 10 seconds.
conf.connectTimeout = 10000;
// Set the read/write timeout to 30 seconds.
conf.readWriteTimeout = 30000;
oss::OSSClient client(conf);
Retry policy
The built-in StandardRetryer uses a FullJitterBackoff strategy with a maximum of 3 retries by default. Use retryMaxAttempts to adjust.
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Set the maximum number of retries to 5.
conf.retryMaxAttempts = 5;
oss::OSSClient client(conf);
Custom retry strategy example: CustomRetryStrategy.cpp.
HTTP/HTTPS protocol
The HTTPS protocol is used by default. To use the HTTP protocol, set disableSsl to true.
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use the HTTP protocol.
conf.disableSsl = true;
oss::OSSClient client(conf);
Use an internal endpoint
When deployed on ECS, use an internal endpoint to avoid public network traffic costs.
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use an internal endpoint.
conf.useInternalEndpoint = true;
oss::OSSClient client(conf);
Use a transfer acceleration endpoint
Use a transfer acceleration endpoint for long-distance data transfers.
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use a transfer acceleration endpoint.
conf.useAccelerateEndpoint = true;
oss::OSSClient client(conf);
Use a custom domain (CNAME)
Access OSS by using a custom domain (CNAME).
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
conf.endpoint = "https://your-custom-domain.com";
conf.useCName = true;
oss::OSSClient client(conf);
Customize the HTTP transport
The SDK uses cURL by default. Replace it via httpTransport. WinHTTP is also supported on Windows.
Custom transport examples: CurlCustomConfig.cpp and WinHttpCustomConfig.cpp.
Configure access credentials
The SDK supports the following credential methods:
RAM user access key
Use a RAM user's access key for applications in a secure, non-internet-exposed environment.
Environment variables (Recommended)
Obtain credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
-
Set the environment variables by using the access key of a RAM user.
Linux
-
From the command line, run the following commands to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Run the following command to apply the changes.
source ~/.bashrc -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
In the terminal, run the following command to check your default shell type.
echo $SHELL -
Follow the steps based on your default shell type.
Zsh
-
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the changes.
source ~/.zshrc -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the changes.
source ~/.bash_profile -
Run the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
In CMD, run the following commands.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Reopen CMD and run the following commands to verify that the environment variables are set.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
In PowerShell, run the following commands.
[System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User) [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User) -
Reopen PowerShell and run the following commands to verify that the environment variables are set.
[System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User) [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)
-
-
After modifying system environment variables, restart your IDE and terminal for changes to take effect.
-
Use the environment variables to pass the credentials.
Before you run the sample code, replace
<region-id>with an actual region ID, such ascn-hangzhou.#include "alibabacloud/oss2/ClientConfiguration.h" #include "alibabacloud/oss2/OSSClient.h" #include "alibabacloud/oss2/credentials/CredentialsProvider.h" namespace oss = alibabacloud::oss2; int main() { auto conf = oss::ClientConfiguration::loadDefault(); conf.region = "<region-id>"; conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>(); oss::OSSClient client(conf); // Use the client to perform operations. return 0; }
Explicitly in code
You can explicitly provide the access key ID and access key secret by using StaticCredentialsProvider.
This method exposes your access key in the code and is recommended for testing purposes only. For production environments, use a more secure method, such as environment variables.
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::StaticCredentialsProvider>(
"YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET");
oss::OSSClient client(conf);
// Use the client to perform operations.
return 0;
}
STS temporary credential
STS temporary credentials consist of an access key ID, access key secret, and security token. You must manually manage and refresh the token.
-
To obtain an STS temporary credential using an SDK, see Use STS temporary credentials to access OSS.
-
When you generate an STS token, you must specify an expiration time. The token automatically becomes invalid after it expires.
-
Note that access key IDs obtained from STS start with the prefix
STS, for example,STS.L4aBSCSJVMuKg5U1****.
Environment variables (Recommended)
Obtain temporary credentials by using the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables.
-
Set the environment variables by using the temporary credentials.
macOS, Linux, or Unix
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
Use the environment variables to pass the credentials. The SDK's
EnvironmentVariableCredentialsProviderautomatically reads these three environment variables.Before you run the sample code, replace
<region-id>with an actual region ID, such ascn-hangzhou.#include "alibabacloud/oss2/ClientConfiguration.h" #include "alibabacloud/oss2/OSSClient.h" #include "alibabacloud/oss2/credentials/CredentialsProvider.h" namespace oss = alibabacloud::oss2; int main() { auto conf = oss::ClientConfiguration::loadDefault(); conf.region = "<region-id>"; // Automatically reads OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN. conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>(); oss::OSSClient client(conf); // Use the client to perform operations. return 0; }
Explicitly in code
You can explicitly provide the temporary access key ID, access key secret, and security token by using StaticCredentialsProvider.
Testing only. Do not embed credentials in production code. Use environment variables or an auto-refreshing SDK method instead.
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::StaticCredentialsProvider>(
"STS_ACCESS_KEY_ID", "STS_ACCESS_KEY_SECRET", "STS_SECURITY_TOKEN");
oss::OSSClient client(conf);
// Use the client to perform operations.
return 0;
}
RAMRoleARN, ECSRAMRole, or OIDCRoleARN
For credential methods such as RAMRoleARN, ECSRAMRole, and OIDCRoleARN, we recommend using the alibabacloud-credentials-cpp library with CredentialsProviderFunc.
-
Install the dependency.
vcpkg install alibabacloud-credentials-cpp -
Add the dependency in your CMakeLists.txt file.
find_package(alibabacloud_credentials REQUIRED) -
Integrate the library by using
CredentialsProviderFunc.RAMRoleARN
#include "alibabacloud/oss2/ClientConfiguration.h" #include "alibabacloud/oss2/OSSClient.h" #include "alibabacloud/oss2/credentials/CredentialsProvider.h" #include <darabonba/core/Client.hpp> #include <alibabacloud/credential.hpp> namespace oss = alibabacloud::oss2; int main() { auto credConfig = std::make_shared<Alibabacloud_Credential::Config>(); // The credential type must be ram_role_arn. credConfig->type = std::make_shared<std::string>("ram_role_arn"); // The access key ID of the RAM user. To avoid hardcoding, we recommend injecting this value through the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. credConfig->accessKeyId = std::make_shared<std::string>("YOUR_ACCESS_KEY_ID"); // The access key secret of the RAM user. To avoid hardcoding, we recommend injecting this value through the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. credConfig->accessKeySecret = std::make_shared<std::string>("YOUR_ACCESS_KEY_SECRET"); // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole // You can also set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable. credConfig->roleArn = std::make_shared<std::string>("YOUR_ROLE_ARN"); // The role session name, used for auditing purposes. You can also set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. credConfig->roleSessionName = std::make_shared<std::string>("your-session-name"); // (Optional) Further restrict permissions with a policy. This parameter is not required. // Example: {"Statement":[{"Action":["oss:GetObject"],"Effect":"Allow","Resource":["*"]}],"Version":"1"} // credConfig->policy = std::make_shared<std::string>("<Policy>"); // (Optional) The role session duration in seconds. Default: 3600 (1 hour). This parameter is not required. // credConfig->roleSessionExpiration = std::make_shared<long>(3600); auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig); auto conf = oss::ClientConfiguration::loadDefault(); conf.region = "<region-id>"; conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>( [credClient]() -> oss::Credentials { auto cred = credClient->getCredential(); auto ak = cred.getAccessKeyId(); auto sk = cred.getAccessKeySecret(); if (ak.empty() || sk.empty()) { return oss::Credentials::withRetryableError( "failed to get credentials from alibabacloud-credentials-cpp"); } auto token = cred.getSecurityToken(); return oss::Credentials(std::move(ak), std::move(sk), std::move(token)); }); oss::OSSClient client(conf); // Use the client to perform operations. return 0; }ECSRAMRole
#include "alibabacloud/oss2/ClientConfiguration.h" #include "alibabacloud/oss2/OSSClient.h" #include "alibabacloud/oss2/credentials/CredentialsProvider.h" #include <darabonba/core/Client.hpp> #include <alibabacloud/credential.hpp> namespace oss = alibabacloud::oss2; int main() { auto credConfig = std::make_shared<Alibabacloud_Credential::Config>(); // The credential type must be ecs_ram_role. credConfig->type = std::make_shared<std::string>("ecs_ram_role"); // The name of the RAM role granted to the ECS instance. This parameter is optional. // If you do not set it, the SDK automatically retrieves it from the metadata service. // We strongly recommend setting this parameter explicitly to reduce requests to the metadata service. credConfig->roleName = std::make_shared<std::string>("YOUR_ECS_ROLE_NAME"); auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig); auto conf = oss::ClientConfiguration::loadDefault(); conf.region = "<region-id>"; conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>( [credClient]() -> oss::Credentials { auto cred = credClient->getCredential(); auto ak = cred.getAccessKeyId(); auto sk = cred.getAccessKeySecret(); if (ak.empty() || sk.empty()) { return oss::Credentials::withRetryableError( "failed to get credentials from alibabacloud-credentials-cpp"); } auto token = cred.getSecurityToken(); return oss::Credentials(std::move(ak), std::move(sk), std::move(token)); }); oss::OSSClient client(conf); // Use the client to perform operations. return 0; }OIDCRoleARN
#include "alibabacloud/oss2/ClientConfiguration.h" #include "alibabacloud/oss2/OSSClient.h" #include "alibabacloud/oss2/credentials/CredentialsProvider.h" #include <darabonba/core/Client.hpp> #include <alibabacloud/credential.hpp> namespace oss = alibabacloud::oss2; int main() { auto credConfig = std::make_shared<Alibabacloud_Credential::Config>(); // The credential type must be oidc_role_arn. credConfig->type = std::make_shared<std::string>("oidc_role_arn"); // The ARN of the RAM role to assume. You can also set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable. credConfig->roleArn = std::make_shared<std::string>("YOUR_ROLE_ARN"); // The ARN of the OIDC identity provider. You can also set this value by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. credConfig->oidcProviderArn = std::make_shared<std::string>("YOUR_OIDC_PROVIDER_ARN"); // The path to the OIDC token file, which is automatically mounted into the pod by RRSA. You can also set this value by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. credConfig->oidcTokenFilePath = std::make_shared<std::string>("/var/run/secrets/tokens/oidc-token"); // The role session name, used for auditing purposes. You can also set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. credConfig->roleSessionName = std::make_shared<std::string>("your-session-name"); // (Optional) Further restrict permissions with a policy. This parameter is not required. // credConfig->policy = std::make_shared<std::string>("<Policy>"); auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig); auto conf = oss::ClientConfiguration::loadDefault(); conf.region = "<region-id>"; conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>( [credClient]() -> oss::Credentials { auto cred = credClient->getCredential(); auto ak = cred.getAccessKeyId(); auto sk = cred.getAccessKeySecret(); if (ak.empty() || sk.empty()) { return oss::Credentials::withRetryableError( "failed to get credentials from alibabacloud-credentials-cpp"); } auto token = cred.getSecurityToken(); return oss::Credentials(std::move(ak), std::move(sk), std::move(token)); }); oss::OSSClient client(conf); // Use the client to perform operations. return 0; }More credential examples: credentials examples.
Anonymous access
Access public-read buckets and objects without credentials.
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::AnonymousCredentialsProvider>();
oss::OSSClient client(conf);
// Use the client to perform operations.
return 0;
}
Custom credential provider
Implement custom credential retrieval logic with CredentialsProviderFunc.
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
#include <cstdlib>
namespace oss = alibabacloud::oss2;
// Example: Load credentials from custom environment variables or a configuration file.
static oss::Credentials loadCredentialsFromCustomSource() {
// In a real-world application, you can retrieve credentials from various sources:
// - A configuration file (such as ~/.ossrc)
// - A key management service (such as HashiCorp Vault or KMS)
// - A metadata service
// - A database
const char* ak = std::getenv("MY_APP_ACCESS_KEY_ID");
const char* sk = std::getenv("MY_APP_ACCESS_KEY_SECRET");
const char* token = std::getenv("MY_APP_SESSION_TOKEN");
if (!ak || !sk) {
// The error message propagates to OperationError::getMessage().
return oss::Credentials::withError(
"MY_APP_ACCESS_KEY_ID and MY_APP_ACCESS_KEY_SECRET must be set");
// For transient failures, such as network timeouts, use withRetryableError.
// The SDK automatically retries credential retrieval.
// return oss::Credentials::withRetryableError("...");
}
return oss::Credentials(ak, sk, token ? token : "");
}
int main() {
// The custom credential provider function is called every time credentials are required,
// allowing you to implement rotation, refresh, or caching logic.
auto provider = std::make_shared<oss::CredentialsProviderFunc>(
loadCredentialsFromCustomSource);
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = provider;
oss::OSSClient client(conf);
// Use the client to perform operations.
return 0;
}
Calling API operations
API operations follow a consistent naming convention and calling pattern.
API naming convention
Method names use camelCase style. Each operation takes an <OperationName>Request parameter and returns an <OperationName>Outcome (Outcome<Result, Error>).
OSSClient (synchronous):
OutcomeType operationName(const models::OperationNameRequest& request, const OperationOptions* options = nullptr)
OSSAsyncClient (native asynchronous):
void operationNameAsync(const models::OperationNameRequest& request, const OperationNameAsyncCallback& callback, const OperationOptions* options = nullptr)
Calling modes
|
Calling mode |
OSSClient |
OSSAsyncClient |
|
synchronous |
|
- |
|
future-based asynchronous |
|
|
|
callback-based asynchronous |
|
|
Canceling a request
To cancel long-running operations with a CancellationToken, pass a cancellationToken in OperationOptions. The OSS C++ SDK V2 provides two cancellation modes:
Cancel immediately
Call CancellationTokenSource::cancel() from another thread to interrupt an in-progress request.
// Cancel the request from another thread.
auto cts = oss::CancellationTokenSource::create();
oss::OperationOptions opts;
opts.cancellationToken = cts->getToken();
// Start the request in another thread.
auto future = std::async([&]() {
return client.getObject(request, &opts);
});
// Cancel from the current thread.
cts->cancel();
Cancel by deadline
Call cancelAfter() to set a timeout. The SDK automatically cancels the request when the timeout expires.
// Set a 30-second timeout for automatic cancellation.
auto cts = oss::CancellationTokenSource::create();
cts->cancelAfter(std::chrono::seconds(30));
oss::OperationOptions opts;
opts.cancellationToken = cts->getToken();
auto outcome = client.getObject(request, &opts);
Error handling
The OSS C++ SDK V2 uses Outcome<Result, Error>, which is compatible with std::expected. Call has_value() to check for success. If successful, retrieve the result with value() or by dereferencing the outcome object (*outcome). Otherwise, retrieve the error object with error().
auto outcome = client.putObject(request);
if (!outcome.has_value()) {
auto& err = outcome.error();
std::cerr << "Error code: " << err.getCode() << std::endl;
std::cerr << "Error message: " << err.getMessage() << std::endl;
std::cerr << "EC: " << err.getEC() << std::endl;
std::cerr << "Request ID: " << err.getRequestId() << std::endl;
std::cerr << "Request target: " << err.getRequestTarget() << std::endl;
}
When you build with the -DUSE_STD_EXPECTED=ON flag (C++23), Outcome becomes a type alias for std::expected, which supports monadic operations such as .and_then(), .transform(), and .or_else().
Sample code
The following table lists the available sample code.
|
Category |
Description |
Synchronous version |
Asynchronous version |
|
Buckets |
Create a bucket |
||
|
List buckets |
|||
|
Delete a bucket |
|||
|
Get bucket information |
|||
|
Get bucket location |
|||
|
Object upload |
Simple upload |
||
|
Append upload |
|||
|
Multipart upload |
|||
|
Multipart copy |
|||
|
Object download |
Simple download |
||
|
Copy an object |
|||
|
Object management |
List objects |
||
|
List objects V2 |
|||
|
Delete an object |
|||
|
Delete multiple objects |
|||
|
Get object metadata |
|||
|
Get simplified object metadata |
|||
|
Archived objects |
Restore an object |
||
|
Delete a restored object |
|||
|
Symbolic links |
Create a symbolic link |
||
|
Get a symbolic link |
|||
|
Object tagging |
Set object tagging |
||
|
Get object tagging |
|||
|
Delete object tagging |
|||
|
Access control |
Set bucket ACL |
||
|
Get bucket ACL |
|||
|
Set object ACL |
|||
|
Versioning |
Set bucket versioning |
||
|
Get bucket versioning status |
|||
|
List object versions |
|||
|
Hotlink protection |
Set hotlink protection |
||
|
Get hotlink protection configuration |
|||
|
System functions |
Query endpoint information |
||
|
Presigned URL |
Generate a presigned URL for download |
- |
|
|
Generate a presigned URL for upload |
- |
||
|
Generate a presigned URL for a HEAD request |
- |
||
|
Generate a presigned URL for multipart upload |
- |
||
|
Generic API |
Using |
- |
|
|
Paginator |
List all buckets |
- |
|
|
List all objects (recommended) |
- |
||
|
List all object versions |
- |
||
|
List all uploaded parts |
- |
||
|
List all multipart uploads |
- |
||
|
List all objects (legacy, not recommended) |
- |
||
|
Scenario examples |
|
- |
|
|
Asynchronous operations with |
- |
||
|
More scenario examples |
- |