All Products
Search
Document Center

Object Storage Service:Initialize an OSSClient instance for using OSS SDK for C++

Last Updated:Jul 05, 2024

OSSClient is used to manage Object Storage Service (OSS) resources such as buckets and objects. To use OSS SDK for C++ to initiate a request, you must initialize an OSSClient instance and modify the default configuration items of ClientConfiguration.

Create an OSSClient instance

Important
  • OSSClient is thread-safe and allows you to use multiple threads to access the same instance. You can reuse the OSSClient instance or create multiple OSSClient instances based on your business requirements.

  • InitializeSdk() and ShutdownSdk() are global operations that need to be called only once during the lifecycle of a program.

(Recommended) Use the V4 signature algorithm

We recommend that you use the V4 signature algorithm which provides better security. If you use the V4 signature algorithm, include the Region parameter. The Region parameter must be an Alibaba Cloud Region ID. Example: cn-Hangzhou. You must also declare SignatureVersionType::V4 at the same time. The OSS SDK for C++ 1.10.0 or later supports the V4 signature algorithm.

The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint and the V4 signature algorithm. To create an OSSClient instance by using a custom domain name or access credentials obtained from Security Token Service (STS), modify the following sample code accordingly.

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

(Not recommended) Use the V1 signature algorithm

Important

From December 1, 2024, the V1 signature algorithm of Object Storage Service (OSS) is no longer available to new customers with new UIDs. From June 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.

Use an OSS endpoint

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);   

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Use a custom domain name

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Set yourEndpoint to the custom domain name that you want to use. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.isCname = true;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);   

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Use temporary access credentials obtained from STS

Temporary access credentials provided by Security Token Service (STS) include a security token and a temporary AccessKey pair. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials from STS, see Use temporary credentials provided by STS to access OSS.

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
        
    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the temporary AccessKey pair and security token are configured by using the environment variables. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf); 

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Configure the OSSClient instance

ClientConfiguration is a configuration class of OSSClient. You can use ClientConfiguration to configure parameters, such as userAgent, connectTimeoutMs, and maxConnections.

You can configure parameters by using OSSClient. The following table describes the parameters.

Parameter

Description

isCname

Specifies whether to use a CNAME as the endpoint. By default, no CNAME is used.

userAgent

The user agent (the User-Agent header). Default value: aliyun-sdk-cpp/1.X.X.

maxConnections

The maximum number of connections. Default value: 16.

requestTimeoutMs

The timeout period of the request. The connection is closed if no data is received throughout the timeout period. Default value: 10000. Unit: milliseconds.

connectTimeoutMs

The timeout period for connection setup. Default value: 5000. Unit: milliseconds.

retryStrategy

The maximum number of allowed retry attempts if a request fails.

proxyScheme

The proxy protocol. Default value: HTTP.

proxyPort

The port that is used to connect to the proxy server.

proxyPassword

The password that is used to log on to the proxy server.

proxyUserName

The username that is used to log on to the proxy server.

verifySSL

Specifies whether to enable SSL-based authentication. By default, SSL-based authentication is disabled.

Note

By default, SSL-based authentication is enabled in OSS SDK for C++ 1.8.2 or later.

caPath

The root path of the CA certificate. This parameter is valid if verifySSL is set to true. By default, this parameter is left empty.

caFile

The path of the CA certificate. This parameter is valid if verifySSL is set to true. By default, this parameter is left empty.

enableCrc64

Specifies whether to enable CRC-64. By default, CRC-64 is enabled.

enableDateSkewAdjustment

Specifies whether to enable automatic correction of HTTP request time. By default, automatic correction of HTTP request time is enabled.

sendRateLimiter

The maximum upload speed. Unit: KB/s.

recvRateLimiter

The maximum download speed. Unit: KB/s.

Configure a timeout period

The following code provides an example on how to configure a timeout period:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();
    ClientConfiguration conf;

    /* Specify the maximum number of connections. Default value: 16. */
    conf.maxConnections = 20;

    /* Specify the request timeout period. The connection is closed if no data is received during the timeout period. Unit: milliseconds. Default value: 10000. */
    conf.requestTimeoutMs = 8000;

    /* Specify the timeout period to establish a connection. Unit: milliseconds. Default value: 5000. */
    conf.connectTimeoutMs = 8000;

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);  

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Configure SSL-based authentication

By default, SSL-based authentication is enabled in OSS SDK for C++ V1.8.2 and later. If SSL-based authentication fails, check whether the path of the SSL certificate is correct or disable SSL-based authentication.

The following sample code provides an example on how to configure SSL-based authentication:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();
    ClientConfiguration conf;

    /* Configure SSL-based authentication. Default value: true. The value true specifies that SSL-based authentication is enabled. */
    conf.verifySSL = true;

    /* Specify the root path of the CA certificate. This parameter is valid if verifySSL is set to true. By default, this parameter is left empty. */
    conf.caPath = "/etc/ssl/certs/";

    /* Specify the path of the CA certificate. This parameter is valid if verifySSL is set to true. By default, this parameter is left empty. */
    conf.caFile = "/etc/ssl/certs/ca-certificates.crt";;

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);  

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Configure bandwidth throttling

The following code provides an example on how to configure bandwidth throttling for uploads and downloads:

#include <alibabacloud/oss/OssClient.h>
#include <alibabacloud/oss/client/RateLimiter.h>

using namespace AlibabaCloud::OSS;

class UserRateLimiter : public RateLimiter
{
public:
    UserRateLimiter() : rate_(0) {};
    ~UserRateLimiter() {};
    virtual void setRate(int rate) { rate_ = rate; };
    virtual int Rate() const { return rate_; };
private:
    int rate_;
};

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;

    auto sendrateLimiter = std::make_shared<UserRateLimiter>();
    auto recvrateLimiter = std::make_shared<UserRateLimiter>();
    conf.sendRateLimiter = sendrateLimiter;
    conf.recvRateLimiter = recvrateLimiter;

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Configure bandwidth throttling for the download. Unit: KB/s. */
    recvrateLimiter->setRate(256);

    /* Configure bandwidth throttling for the upload. Unit: KB/s. */
    sendrateLimiter->setRate(256);

    /* Upload the object. Specify the full path of the local file. */
    auto outcome = client.PutObject(BucketName, ObjectName, "yourLocalFilename");  

    /* Update the speed limit during the upload. Unit: KB/s. */
    sendrateLimiter->setRate(300);

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Configure a retry policy

The following sample code provides an example on how to configure a retry policy:

#include <alibabacloud/oss/OssClient.h>
#include <alibabacloud/oss/client/RetryStrategy.h>

using namespace AlibabaCloud::OSS;

class UserRetryStrategy : public RetryStrategy
{
public:

    /* maxRetries indicates the maximum number of allowed retry attempts. scaleFactor indicates the factor that is used to calculate the waiting time before a retry is attempted. */
    UserRetryStrategy(long maxRetries = 3, long scaleFactor = 300) :
        m_scaleFactor(scaleFactor), m_maxRetries(maxRetries)  
    {}

    /* You can specify the shouldRetry function to determine whether to retry a request. */
    bool shouldRetry(const Error & error, long attemptedRetries) const;

    /* You can specify the calcDelayTimeMs function to calculate the waiting time before a retry is attempted. */
    long calcDelayTimeMs(const Error & error, long attemptedRetries) const;

private:
    long m_scaleFactor;
    long m_maxRetries;
};

bool UserRetryStrategy::shouldRetry(const Error & error, long attemptedRetries) const
{    
    if (attemptedRetries >= m_maxRetries)
        return false;

    long responseCode = error.Status();

    //http code
    if ((responseCode == 403 && error.Message().find("RequestTimeTooSkewed") != std::string::npos) ||
        (responseCode > 499 && responseCode < 599)) {
        return true;
    }
    else {
        switch (responseCode)
        {
        //curl error code
        case (ERROR_CURL_BASE + 7):  //CURLE_COULDNT_CONNECT
        case (ERROR_CURL_BASE + 18): //CURLE_PARTIAL_FILE
        case (ERROR_CURL_BASE + 23): //CURLE_WRITE_ERROR
        case (ERROR_CURL_BASE + 28): //CURLE_OPERATION_TIMEDOUT
        case (ERROR_CURL_BASE + 52): //CURLE_GOT_NOTHING
        case (ERROR_CURL_BASE + 55): //CURLE_SEND_ERROR
        case (ERROR_CURL_BASE + 56): //CURLE_RECV_ERROR
            return true;
        default:
            break;
        };
    }

    return false;
}

long UserRetryStrategy::calcDelayTimeMs(const Error & error, long attemptedRetries) const
{
    return (1 << attemptedRetries) * m_scaleFactor;
}

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();
    ClientConfiguration conf;

    /* Specify the maximum number of allowed retry attempts if a request fails. Default value: 3. */
    auto defaultRetryStrategy = std::make_shared<UserRetryStrategy>(5);
    conf.retryStrategy = defaultRetryStrategy;

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);  

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Configure a proxy server

The following sample code provides an example on how to configure a proxy server:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Initialize resources, such as network resources. */
    InitializeSdk();
    ClientConfiguration conf;

    /* Specify the address of the proxy server. */
    conf.proxyHost = "yourProxyHost";

    /* Set the port for the proxy server. */
    conf.proxyPort = 1234;

    /* Optional. Specify the username for proxy server authentication. */
    conf.proxyUserName = "yourProxyUserName";

    /* Optional. Specify the password for proxy server authentication. */
    conf.proxyPassword = "yourProxyPassword";

    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);  

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}