Todos os produtos
Search
Central de documentação

Object Storage Service:Inicialização (SDK C++)

Última atualização: Jul 03, 2026

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

Criar uma instância de OssClient

Importante
  • A classe OssClient é thread-safe, o que permite usar múltiplas threads para acessar a mesma instância. Reutilize a mesma instância de OssClient ou crie várias instâncias conforme necessário.

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

(Recomendado) Assinatura V4

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

O código a seguir exemplifica a criação de uma instância de OssClient com um nome de domínio do OSS e assinatura V4. Para usar um nome de domínio personalizado ou credenciais do Security Token Service (STS), adapte o exemplo adequadamente.

#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

Criar uma instância de 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;
}

Criar uma instância de 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;
}

Criar uma instância de OssClient usando STS

As credenciais de acesso temporário fornecidas pelo Security Token Service (STS) consistem em um par de AccessKey temporário (AccessKey ID e AccessKey secret) e um token de segurança. Para obter mais informações sobre como adquirir credenciais de acesso temporário no STS, consulte Usar credenciais temporárias fornecidas pelo STS para acessar o 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;
}

Configurar o OssClient

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

Defina os seguintes parâmetros para o OssClient:

Parâmetro

Descrição

isCname

Define se um CNAME deve ser usado como endpoint. Por padrão, esse recurso não tem suporte.

userAgent

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

maxConnections

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

requestTimeoutMs

Tempo limite da solicitação em milissegundos. Se nenhum dado for recebido nesse período, a conexão será encerrada. O valor padrão é 10.000 ms.

connectTimeoutMs

Tempo limite para estabelecimento de conexão. O valor padrão é 5.000 ms.

retryStrategy

Política de nova tentativa personalizada para solicitações com falha.

proxyScheme

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

proxyPort

Porta do servidor proxy.

proxyPassword

Senha para autenticação no servidor proxy.

proxyUserName

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

verifySSL

Indica se a verificação de certificado SSL deve ser ativada. Por padrão, esse recurso está desativado.

Nota

A verificação de certificado SSL vem habilitada por padrão no SDK C++ versão 1.8.2 e posteriores.

caPath

Caminho raiz do certificado da CA. Este parâmetro só tem efeito quando verifySSL está definido como true. Por padrão, este parâmetro está vazio.

caFile

Caminho do certificado da CA. Este parâmetro só tem efeito quando verifySSL está definido como true. Por padrão, este parâmetro está vazio.

enableCrc64

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

enableDateSkewAdjustment

Habilita a correção automática para discrepância de horário em solicitações HTTP. Por padrão, esse recurso está ativado.

sendRateLimiter

Limite de velocidade de upload em KB/s.

recvRateLimiter

Limite de velocidade de download em KB/s.

Definir o tempo limite

O código a seguir exemplifica 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;
}

Configurar a verificação de certificado SSL

O SDK C++ versão 1.8.2 e posteriores habilita a verificação de certificado SSL por padrão. Caso a verificação falhe, defina o caminho correto do certificado ou desative a verificação de certificado SSL.

O código a seguir demonstra 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;
}

Definir limites de taxa

O código a seguir ilustra como estabelecer limites de taxa para uploads ou 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;
}

Definir uma política de nova tentativa

O código abaixo configura a política de nova tentativa:

#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;
}

Configurar 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;
}