Todos os produtos
Search
Central de documentação

Object Storage Service:Inicialização (Android SDK)

Última atualização: Jul 13, 2026

O OSSClient é o cliente Android para o service OSS. Ele fornece métodos para gerenciar buckets e objetos. Antes de usar o kit de desenvolvimento de software (SDK) para enviar solicitações ao OSS, inicialize uma instância do OSSClient e defina suas configurações.

Nota

O ciclo de vida do OSSClient deve corresponder ao ciclo de vida do aplicativo. Crie um OSSClient global ao iniciar o aplicativo e destrua-o ao encerrar a aplicação.

Inicializar o OSSClient

Importante

Dispositivos móveis são ambientes não confiáveis. Armazenar o AccessKeyId e o AccessKeySecret diretamente no dispositivo para assinar solicitações representa alto risco de segurança. Recomendamos usar o modo de autenticação do Security Token Service (STS) ou o modo autoassinado.

Credenciais temporárias do STS também podem ser extraídas após chegarem ao cliente móvel. Portanto, restrinja-as com uma política do RAM que limite as permissões a um único usuário e defina um curto período de validade. Em cenários com dados sensíveis, como documentos de identidade, imagens faciais ou credenciais de pagamento, configure o servidor de aplicativos para gerar uma URL pré-assinada para o aplicativo móvel. Assim, o aplicativo nunca armazena credenciais. Para selecionar o provedor de credenciais, consulte Configurar credenciais de acesso (Android SDK). Para URLs pré-assinadas, consulte Autorizar acesso (Android SDK).

Crie um OSSClient das seguintes maneiras:

Nota

Para aprender a chamar interfaces de operações como upload e download, consulte Início rápido (Android SDK).

A inicialização do OSSClient para listar buckets difere do método geral destes exemplos. Para mais informações, consulte Listar buckets (Android SDK).

Criar um OSSClient usando STS

O código abaixo demonstra como criar um OSSClient com STS.

// 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.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region 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.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Criar um OSSClient usando um nome de domínio personalizado

O exemplo a seguir ilustra a criação de um OSSClient com nome de domínio personalizado.

// Set yourEndpoint to the custom domain name.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region 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.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Criar um OSSClient em um ambiente Apsara Stack ou de domínio privado

Veja a seguir como criar um OSSClient em ambiente Apsara Stack ou de domínio privado.

// Set yourEndpoint to the Endpoint of the region where the bucket is located.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region 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.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration configuration = new ClientConfiguration();
// Skip CNAME parsing.
List<String> excludeList = new ArrayList<>();
excludeList.add(endpoint);
configuration.setCustomCnameExcludeList(excludeList);
// Create an OSSClient instance.
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Configurar o OSSClient

A classe ClientConfiguration define as configurações do OSSClient. Utilize-a para ajustar parâmetros como proxy, tempo limite de conexão e número máximo de conexões.

Parâmetro

Descrição

Método

maxConcurrentRequest

Número máximo de solicitações simultâneas. Valor padrão: 5.

ClientConfiguration.setMaxConcurrentRequest

socketTimeout

Tempo limite para transmissão de dados na camada de soquete, em milissegundos. Valor padrão: 60000.

ClientConfiguration.setSocketTimeout

connectionTimeout

Tempo limite para estabelecer conexão, em milissegundos. Valor padrão: 60000.

ClientConfiguration.setConnectionTimeout

max_log_size

Tamanho do arquivo de log. Valor padrão: 5 MB.

ClientConfiguration.setMaxLogSize

maxErrorRetry

Número máximo de tentativas após falha na solicitação. Valor padrão: 2.

ClientConfiguration.setMaxErrorRetry

customCnameExcludeList

Elementos nesta lista ignoram a resolução de canonical name (CNAME).

ClientConfiguration.setCustomCnameExcludeList

proxyHost

Endereço do host do servidor proxy.

ClientConfiguration.setProxyHost

proxyPort

Porta do servidor proxy.

ClientConfiguration.setProxyPort

mUserAgentMark

Cabeçalho User-Agent HTTP no user agent.

ClientConfiguration.setUserAgentMark

httpDnsEnable

Define se o HTTPDNS está ativado.

  • true: HTTPDNS ativado por padrão em versões anteriores à 2.9.12.

  • false: HTTPDNS desativado por padrão nas versões 2.9.12 e posteriores.

ClientConfiguration.setHttpDnsEnable

checkCRC64

Ativa a verificação de redundância cíclica de 64 bits (CRC-64). Valores válidos:

  • true: Ativa o CRC-64.

  • false (padrão): Desativa o CRC-64.

ClientConfiguration.setCheckCRC64

followRedirectsEnable

Ativa o redirecionamento HTTP. Valores válidos:

  • true: Ativa o redirecionamento HTTP.

  • false (padrão): Desativa o redirecionamento HTTP.

ClientConfiguration.setFollowRedirectsEnable

okHttpClient

Um okHttpClient personalizado.

ClientConfiguration.setOkHttpClient

O código a seguir exemplifica o uso da classe ClientConfiguration para definir os parâmetros do OSSClient.

// 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.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region 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.
String region = "yourRegion";

ClientConfiguration configuration = new ClientConfiguration();
// Set the maximum number of concurrent requests. Default value: 5.
// configuration.setMaxConcurrentRequest(3);
// Set the timeout period for data transmission at the socket layer. Default value: 60s.
// configuration.setSocketTimeout(50000);
// Set the timeout period for establishing a connection. Default value: 60s.
// configuration.setConnectionTimeout(50000);
// Set the size of the log file. Default value: 5 MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);
// Set the maximum number of retries after a request fails. Default value: 2.
// configuration.setMaxErrorRetry(3);
// Elements in the list will skip CNAME parsing.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// The host address of the proxy server.
// configuration.setProxyHost("yourProxyHost");
// The port of the proxy server.
// configuration.setProxyPort(8080);
// The User-Agent header of HTTP in the user agent.
// configuration.setUserAgentMark("yourUserAgent");
// Specifies whether to enable cyclic redundancy check (CRC). Default value: false.
// configuration.setCheckCRC64(true);
// Specifies whether to enable HTTP redirection. Default value: false.
// configuration.setFollowRedirectsEnable(true);
// Set a custom OkHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Ativar logs

O ambiente móvel é complexo e o SDK do OSS pode apresentar falhas em certas regiões ou períodos. Para facilitar a identificação de problemas, o SDK registra logs localmente quando esse recurso está ativo. Inicialize o registro de logs antes de usar o OSSClient. Chame o método conforme mostrado abaixo.

// Log style.
// Call OSSLog.enableLog() to enable viewing logs in the console.
// You can write log files to the \OSSLog\logs.csv path on the phone's built-in SD card. This is disabled by default.
// Logs record request data, response data, and exception information for OSS operations.
// For example, requestId and response header.
// The following is a sample log record.
// Android version.
// android_version: 5.1  
// Android phone model.
// mobile_model: XT1085
// Network status.  
// network_state: connected
// Network connection type.
// network_type: WIFI 
// Specific operation behavior information.
// [2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid. 
// A bucket name must: 
// 1) be comprised of lower-case characters, numbers or dash(-); 
// 2) start with lower case or numbers; 
// 3) be between 3-63 characters long. 
//------>end of log
// Call this method to enable logging.
OSSLog.enableLog();              
Nota

Envie os arquivos para seu servidor ou utilize o Alibaba Cloud Simple Log Service para fazer upload dos logs.

Interfaces síncronas e assíncronas

O SDK do Android oferece exemplos de chamadas síncronas e assíncronas para interfaces de upload e download, pois solicitações de rede não são permitidas na thread de UI em aplicativos móveis. Para as demais interfaces, predominam os exemplos assíncronos.

  • Chamada síncrona

    • Bloqueia a thread até o retorno do resultado.

    • Não execute interfaces síncronas na thread de UI.

    • Exceções lançam diretamente uma ClientException ou ServiceException. A ClientException indica erro local, como falha de conectividade ou parâmetro inválido. Já a ServiceException sinaliza erro no service OSS, como falha de autenticação ou problema no servidor.

  • Chamada assíncrona

    • Recebe uma função de callback durante a solicitação para processar o resultado.

    • Trata exceções dentro da própria função de callback.

    • Retorna imediatamente um objeto Task.

      OSSAsyncTask task = oss.asyncGetObejct(...);
      task.cancel(); // Cancel the task.
      task.waitUntilFinished(); // Wait until the task is complete.
      GetObjectResult result = task.getResult(); // Block the thread and wait for the result.