Todos os produtos
Search
Central de documentação

Object Storage Service:Initialization (C++ SDK)

Última atualização: Sep 22, 2026

A classe OssClient gerencia recursos do Object Storage Service (OSS), como buckets e objetos. Antes de enviar uma requisição ao OSS com o SDK C++, inicialize uma instância do OssClient e, se necessário, modifique as configurações padrão do ClientConfiguration.

Crie uma instância do OssClient

Importante
  • A classe OssClient é segura para threads, o que permite usar várias threads para acessar a mesma instância. Reutilize a mesma instância do OssClient ou crie várias instâncias conforme necessário.

  • InitializeSdk() e ShutdownSdk() são funções globais. Chame essas funções apenas uma vez durante o ciclo de vida do programa.

(Recomendado) Assinatura V4

Recomendamos o uso do algoritmo de assinatura V4, que é mais seguro. Ao inicializar uma instância com a assinatura V4, especifique o endpoint e o ID da região da Alibaba Cloud para a requisição. Por exemplo, o ID da região pode ser cn-hangzhou. Também declare SignatureVersionType::V4. As versões 1.10.0 e posteriores do SDK C++ oferecem suporte a assinaturas V4.

O código a seguir mostra como criar uma instância do OssClient usando um nome de domínio do OSS e uma assinatura V4. Para usar um nome de domínio personalizado ou credenciais do Security Token Service (STS), adapte o exemplo conforme necessário.

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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 this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

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

(Não recomendado) Assinatura V1

Importante

A partir de 1º de março de 2025, o Object Storage Service (OSS) da Alibaba Cloud deixou de oferecer a assinatura V1 para novos usuários (novos UIDs). A partir de 1º de setembro de 2025, o OSS deixará de atualizar e manter a assinatura V1 e também deixará de oferecê-la para novos buckets de armazenamento de objetos. Migre para a assinatura V4 o mais rápido possível para evitar interrupções no serviço. Para obter mais informações, consulte Announcement.

Crie uma instância do OssClient usando um nome de domínio do OSS

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is 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 this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);   

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

Crie uma instância do OssClient usando um nome de domínio personalizado

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the custom domain name. */
    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 this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);   

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

Crie uma instância do OssClient usando o STS

As credenciais de acesso temporárias fornecidas pelo Security Token Service (STS) consistem em um par de AccessKey temporário (um AccessKey ID e um AccessKey secret) e um token de segurança. Para obter mais informações sobre como obter credenciais de acesso temporárias do STS, consulte Use temporary credentials provided by STS to access OSS.

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

int main(void)
{
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is 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 this code, make sure that the temporary AccessKey pair and security token are set as environment variables. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf); 

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

Configure o OssClient

A classe ClientConfiguration é responsável por configurar o OssClient. Use-a para definir parâmetros como proxy, tempo limite de conexão e número máximo de conexões.

É possível configurar os seguintes parâmetros do OssClient:

Parâmetro

Descrição

isCname

Define se um CNAME será usado como endpoint. Por padrão, esse recurso não é compatível.

userAgent

O user agent, correspondente ao cabeçalho User-Agent em HTTP. O valor padrão é aliyun-sdk-cpp/1.X.X.

maxConnections

O tamanho do pool de conexões. O valor padrão é 16.

requestTimeoutMs

O tempo limite da requisição em milissegundos. Se nenhum dado for recebido dentro desse período, a conexão será fechada. O valor padrão é 10.000 ms.

connectTimeoutMs

O tempo limite para estabelecer uma conexão. O valor padrão é 5.000 ms.

retryStrategy

Uma política de retentativa personalizada para requisições com falha.

proxyScheme

O protocolo do proxy. O valor padrão é HTTP.

proxyPort

A porta do servidor proxy.

proxyPassword

A senha para autenticação no servidor proxy.

proxyUserName

O nome de usuário para autenticação no servidor proxy.

verifySSL

Define se a verificação de certificado SSL será ativada. Por padrão, esse recurso fica desativado.

Nota

Por padrão, a verificação de certificado SSL é ativada nas versões 1.8.2 e posteriores do SDK C++.

caPath

O caminho raiz do certificado CA. Este parâmetro só tem efeito quando verifySSL é definido como true. Por padrão, fica vazio.

caFile

O caminho do certificado CA. Este parâmetro só tem efeito quando verifySSL é definido como true. Por padrão, fica vazio.

enableCrc64

Define se a verificação de redundância cíclica de 64 bits (CRC64) será ativada. Por padrão, esse recurso fica ativado.

enableDateSkewAdjustment

Define se a correção automática de defasagem de tempo em requisições HTTP será ativada. Por padrão, esse recurso fica ativado.

sendRateLimiter

O limite de velocidade de upload em KB/s.

recvRateLimiter

O limite de velocidade de download em KB/s.

Defina o tempo limite

O código a seguir mostra como definir o tempo limite:

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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;

    /* Set the size of the connection pool. The default value is 16. */
    conf.maxConnections = 20;

    /* Set the request timeout period. If no data is received within this period, the connection is closed. The default value is 10,000 ms. */
    conf.requestTimeoutMs = 8000;

    /* Set the timeout period for establishing a connection. The default value is 5,000 ms. */
    conf.connectTimeoutMs = 8000;

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

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

Defina a verificação de certificado SSL

As versões 1.8.2 e posteriores do SDK C++ ativam a verificação de certificado SSL por padrão. Se a verificação falhar, defina o caminho correto do certificado ou desative a verificação de certificado SSL.

O código a seguir mostra como configurar a verificação de certificado SSL:

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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;

    /* Set the switch for SSL certificate verification. The default value is true, which enables verification. */
    conf.verifySSL = true;

    /* Set the root path of the CA certificate. This parameter takes effect only when verifySSL is set to true. By default, this parameter is empty. */
    conf.caPath = "/etc/ssl/certs/";

    /* Set the path of the CA certificate. This parameter takes effect only when verifySSL is set to true. By default, this parameter is empty. */
    conf.caFile = "/etc/ssl/certs/ca-certificates.crt";;

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

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

Defina limites de taxa

O código a seguir mostra como definir limites de taxa para uploads e 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 OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the full path of the object. The path cannot include the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;

    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 this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set the download rate limit in KB/s. */
    recvrateLimiter->setRate(256);

    /* Set the upload rate limit in KB/s. */
    sendrateLimiter->setRate(256);

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

    /* Update the upload rate limit in KB/s during the upload. */
    sendrateLimiter->setRate(300);

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

Defina uma política de retentativa

O código a seguir define a política de retentativa:

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

using namespace AlibabaCloud::OSS;

class UserRetryStrategy : public RetryStrategy
{
public:

    /* maxRetries specifies the maximum number of retries. scaleFactor is the scaling factor for the retry interval. */
    UserRetryStrategy(long maxRetries = 3, long scaleFactor = 300) :
        m_scaleFactor(scaleFactor), m_maxRetries(maxRetries)  
    {}

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

    /* You can customize the calcDelayTimeMs function to calculate the delay before a retry. */
    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
        case (ERROR_CURL_BASE + 65): //CURLE_SEND_FAIL_REWIND
            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 OSS account information. */
            
   /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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;

    /* Set the number of retries for failed requests. The default value is 3. */
    auto defaultRetryStrategy = std::make_shared<UserRetryStrategy>(5);
    conf.retryStrategy = defaultRetryStrategy;

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

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

Defina um servidor proxy

Use o código a seguir para configurar um servidor proxy:

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

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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;

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

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

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

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

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

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