Todos os produtos
Search
Central de documentação

Object Storage Service:OSS Kotlin SDK V2 (Preview)

Última atualização: Aug 03, 2026

Integre o Alibaba Cloud OSS às suas aplicações Kotlin e Android com o OSS Kotlin SDK V2 para upload, baixe e gerenciamento de arquivos.

GitHub | Guia do desenvolvedor do OSS Kotlin SDK V2

Início rápido

Comece a usar o OSS Kotlin SDK V2:

image

Pré-requisitos

  • Kotlin: 2.1.0 ou superior

  • Java: Java 8+ em tempo de execução (Java 11+ para compilar a partir do código-fonte)

  • Plataformas compatíveis: JVM (Desktop / Server), Android, JavaScript (Node.js e navegadores), WebAssembly (wasmJs para Node.js e navegadores), iOS (iosArm64 e iosSimulatorArm64) e macOS (macosArm64)

Verifique a versão do Kotlin no arquivo build.gradle.kts . Atualize-a caso seja anterior à 2.1.0.

Instale o SDK

Instale o OSS Kotlin SDK V2 com Gradle (recomendado).

Opção 1: Dependência Gradle (recomendada)

Adicione a dependência ao build.gradle.kts:

dependencies {
    implementation("com.aliyun:kotlin-oss-v2:<latest-version>")

    // For extended features (such as the cross-origin resource sharing API)
    // implementation("com.aliyun:kotlin-oss-v2-extension:0.1.0-dev")
}

Pacotes:

  • kotlin-oss-v2: APIs principais para operações de bucket, operações de objeto e recursos avançados (paginadores, pré-assinatura)

  • kotlin-oss-v2-extension: APIs de extensão para recursos de configuração de bucket, como CORS, logging, inventário e estilos de imagem

Opção 2: Compilar a partir do código-fonte

Clone a versão mais recente do OSS Kotlin SDK V2 do GitHub e compile com Gradle:

# Clone the project
$ git clone https://github.com/aliyun/alibabacloud-oss-kotlin-sdk-v2.git

# Enter the directory
$ cd alibabacloud-oss-kotlin-sdk-v2/

# Publish to MavenLocal
$ ./gradlew clean publishToMavenLocal

Adicione mavenLocal à configuração do repositório:

repositories {
    ...
    mavenLocal()
}

Adicione a dependência ao projeto:

implementation("com.aliyun:kotlin-oss-v2:<latest-version>")
// implementation("com.aliyun:kotlin-oss-v2-extension:<latest-version>")

Opção 3: Importação manual de dependências

# Clone the project
$ git clone https://github.com/aliyun/alibabacloud-oss-kotlin-sdk-v2.git

# Enter the directory
$ cd aliyun-oss-kotlin-sdk-v2/

# Run the packaging script
$ ./gradlew :oss-sdk:assemble
# ./gradlew :oss-sdk-extension:assemble

# Using aar as an example
# Enter the build output directory where the package is generated
$ cd oss-sdk/build/outputs/aar && ls
# cd oss-sdk-extension/build/outputs/aar && ls

Configure credenciais de acesso

Armazene o par de AccessKey de um usuário RAM como variáveis de ambiente.

Crie um usuário RAM com acesso permanente via AccessKey no RAM console , salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário.

Linux

  1. Anexe as variáveis de ambiente ao arquivo ~/.bashrc.

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Aplique as alterações.

    source ~/.bashrc
  3. Verifique as variáveis de ambiente.

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Verifique seu shell padrão.

    echo $SHELL
  2. Prossiga conforme o shell padrão.

    Zsh

    1. Anexe as variáveis de ambiente ao arquivo ~/.zshrc.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Aplique as alterações.

      source ~/.zshrc
    3. Verifique as variáveis de ambiente.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    Bash

    1. Anexe as variáveis de ambiente ao arquivo ~/.bash_profile.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. Aplique as alterações.

      source ~/.bash_profile
    3. Verifique as variáveis de ambiente.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Execute os comandos a seguir no CMD.

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Verifique as variáveis de ambiente.

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. Execute os comandos a seguir no PowerShell.

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Verifique as variáveis de ambiente.

    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Inicializar o cliente

Inicialize o OSSClient com Regions and endpoints.

  • O OSSClient implementa Closeable. Ao usá-lo com a função de extensão use, os recursos são liberados automaticamente sem necessidade de chamar close.

  • Crie e destruir o OSSClient é uma operação custosa. Reutilize uma instância singleton e chame close antes de encerrar a aplicação para evitar vazamento de recursos.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider
import com.aliyun.kotlin.sdk.service.oss2.models.ListBucketsRequest
import com.aliyun.kotlin.sdk.service.oss2.paginator.listBucketsPaginator

suspend fun main() {
    val region = "cn-hangzhou"

    // Use the SDK default configuration
    // Load credentials from environment variables
    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
    }

    OSSClient.create(config).use { client ->
        // Use the paginator to list all buckets
        client.listBucketsPaginator(ListBucketsRequest {}).collect { result ->
            result.buckets?.forEach { bucket ->
                println("bucket: name:${bucket.name}, region:${bucket.region}, storageClass:${bucket.storageClass}")
            }
        }
    }
}

A saída lista todos os buckets em todas as regiões da conta:

bucket: name: examplebucket01, region: cn-hangzhou, storageClass: Standard
bucket: name: examplebucket02, region: cn-hangzhou, storageClass: Standard

Configuração do cliente

Quais configurações o cliente suporta?

Parâmetro

Descrição

region

(Obrigatório) Região de destino das requisições

credentialsProvider

(Obrigatório) Provedor de credenciais

endpoint

URL do endpoint

httpTransport

Camada de transporte HTTP

retryMaxAttempts

Número máximo de tentativas de requisição HTTP. Padrão: 3

retryer

Implementação de nova tentativa para requisições HTTP

connectTimeout

Tempo limite de conexão. Padrão: 10 segundos

readWriteTimeout

Tempo limite de leitura/escrita. Padrão: 20 segundos

insecureSkipVerify

Ignorar verificação de certificado SSL. Padrão: false

enabledRedirect

Ativar redirecionamento HTTP. Padrão: false

proxyHost

Servidor proxy

signatureVersion

Versão da assinatura. Padrão: v4

disableSsl

Usar HTTP em vez de HTTPS. Padrão: false (HTTPS)

usePathStyle

Usar URLs no estilo de caminho. Padrão: estilo virtual-hosted

useCName

Usar nome de domínio personalizado. Padrão: false

useDualStackEndpoint

Usar endpoint dual-stack. Padrão: false

useAccelerateEndpoint

Usar endpoint de aceleração de transferência. Padrão: false

useInternalEndpoint

Usar endpoint interno. Padrão: false

additionalHeaders

Cabeçalhos adicionais para assinar. Válido apenas com assinaturas V4

userAgent

Informações adicionais de User-Agent

disableUploadCRC64Check

Desativar verificação CRC64 de upload. Padrão: ativado

disableDownloadCRC64Check

Desativar verificação CRC64 de baixe. Padrão: ativado

Usar um nome de domínio personalizado

Um nome de domínio personalizado permite visualização direta no navegador e aceleração via CDN para arquivos hospedados no OSS.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Specify the region where the bucket is located. For example, for China East 1 (Hangzhou), set Region to cn-hangzhou
    val region = "cn-hangzhou"
    
    // Enter your custom domain. For example, www.example-***.com
    val endpoint = "https://www.example-***.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        this.endpoint = endpoint
        // Note: set this to true to enable the CNAME option; otherwise the custom domain cannot be used
        this.useCName = true
        credentialsProvider = EnvironmentVariableCredentialsProvider()
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Configurações de tempo limite

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider
import kotlin.time.Duration.Companion.seconds

suspend fun main() {
    val region = "cn-hangzhou"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
        // Set the connection establishment timeout; default is 10 seconds
        connectTimeout = 30.seconds
        // Set the timeout for reading/writing data in the application; default is 20 seconds
        readWriteTimeout = 30.seconds
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Política de nova tentativa

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider
import com.aliyun.kotlin.sdk.service.oss2.retry.StandardRetryer
import com.aliyun.kotlin.sdk.service.oss2.retry.FullJitterBackoff
import com.aliyun.kotlin.sdk.service.oss2.retry.FixedDelayBackoff
import com.aliyun.kotlin.sdk.service.oss2.retry.NopRetryer
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds

suspend fun main() {
    /*
     * SDK retry policy configuration:
     *
     * Default retry policy:
     * When no retry policy is configured, the SDK uses StandardRetryer as the client's default implementation, with the following default configuration:
     * - maxAttempts: sets the maximum number of attempts. Defaults to 3
     * - maxBackoff: sets the maximum backoff time. Defaults to 20 seconds
     * - baseDelay: sets the base delay. Defaults to 200 milliseconds
     * - backoffDelayer: sets the backoff algorithm. Uses the FullJitter backoff algorithm by default
     *   Calculation formula: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff)
     * - errorRetryable: the retryable error types, including HTTP status codes, service error codes, client errors, and so on
     *
     * When a retryable error occurs, the provided configuration is used to delay and then retry the request.
     * The overall request delay increases with the number of retries. If the default configuration does not meet your needs,
     * You can configure the retry parameters or modify the retry implementation.
     */

    val region = "cn-hangzhou"

    // Example of configuring a retry policy:

    // 1. Customize the maximum number of retries (default is 3; set to 5 here)
    val customRetryer = StandardRetryer.newBuilder()
        .setMaxAttempts(5)
        .build()

    // 2. Customize the backoff delay
    // Adjust the base delay baseDelay to 500 milliseconds (default 200 ms) and the maximum backoff maxBackoff to 25 seconds (default 20 s)
    // val customRetryer = StandardRetryer.newBuilder()
    //     .setBackoffDelayer(FullJitterBackoff(500.milliseconds, 25.seconds))
    //     .build()

    // 3. Customize the backoff algorithm
    // Use a fixed-delay backoff algorithm instead of the default FullJitter algorithm, with a 2-second delay each time
    // val customRetryer = StandardRetryer.newBuilder()
    //     .setBackoffDelayer(FixedDelayBackoff(2.seconds))
    //     .build()

    // 4. Disable the retry policy
    // To disable all retry attempts, use the NopRetryer implementation
    // val customRetryer = NopRetryer()

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
        retryer = customRetryer
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Protocolo HTTP/HTTPS

Defina disableSsl = true para usar HTTP em vez de HTTPS.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    val region = "cn-hangzhou"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
        // Disable HTTPS requests
        disableSsl = true
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar um endpoint interno

Use a rede interna para acessar recursos do OSS na mesma região, reduzindo custos de tráfego e melhorando o desempenho.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Approach 1: specify Region and set useInternalEndpoint to true
    val region = "cn-hangzhou"

    // Approach 2: specify Region and Endpoint directly
    // val region = "cn-hangzhou"
    // val endpoint = "oss-cn-hangzhou-internal.aliyuncs.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
        useInternalEndpoint = true
        // If you use approach 2, uncomment the next line and comment out the line above
        // this.endpoint = endpoint
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar aceleração de transferência

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Approach 1: specify Region and set useAccelerateEndpoint to true
    val region = "cn-hangzhou"

    // Approach 2: specify Region and the transfer acceleration Endpoint directly
    // val region = "cn-hangzhou"
    // val endpoint = "https://oss-accelerate.aliyuncs.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        credentialsProvider = EnvironmentVariableCredentialsProvider()
        useAccelerateEndpoint = true
        // If you use approach 2, uncomment the next line and comment out the line above
        // this.endpoint = endpoint
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar um domínio dedicado

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    val region = "cn-hangzhou"
    
    // Enter your private domain. For example: https://service.corp.example.com
    val endpoint = "https://service.corp.example.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        this.endpoint = endpoint
        credentialsProvider = EnvironmentVariableCredentialsProvider()
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar um endpoint da China Government Cloud

Configure o OSSClient com um endpoint da Regions and endpoints.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Specify the region where the bucket is located. For example, for China North 2 Alibaba Gov Cloud 1, set Region to cn-north-2-gov-1
    val region = "cn-north-2-gov-1"
    
    // Specify the internal endpoint for the region where the bucket is located. For example, for China North 2 Alibaba Gov Cloud 1
    // To use the HTTP protocol, specify the domain as 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'
    val endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        this.endpoint = endpoint
        credentialsProvider = EnvironmentVariableCredentialsProvider()
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Configuração de credenciais de acesso

O OSS Kotlin SDK V2 suporta vários tipos de credenciais. Escolha um com base nos requisitos de segurança e acesso.

Como escolher um tipo de credencial?

Tipo de credencial

Cenário

Suporte no Kotlin SDK V2

Credencial subjacente

Validade

Rotação ou atualização

Use the AccessKey of a RAM user

Ambientes seguros e estáveis que exigem acesso de longo prazo sem rotação frequente de credenciais

Nativo

AK

Longo prazo

Rotação manual

Use STS temporary credentials

Ambientes não confiáveis que exigem duração de acesso e permissões controladas

Nativo

STS Token

Temporário

Atualização manual

Use custom credentials

Quando nenhum dos tipos de credencial acima atende às necessidades

Nativo

Personalizado

Personalizado

Personalizado

Anonymous access

Acessar recursos de leitura pública sem credenciais

Nativo

N/A

N/A

N/A

Usar o AccessKey de um usuário RAM

Para aplicações em ambientes seguros e estáveis que precisam de acesso de longo prazo ao OSS, inicialize o provedor de credenciais com o par de AccessKey de um usuário RAM (AccessKey ID e AccessKey Secret). Isso requer gerenciamento e rotação manuais das chaves.

Importante
  • Uma conta Alibaba Cloud tem acesso total a todos os recursos. Um AccessKey vazado representa risco significativo de segurança. Use um AccessKey de usuário RAM com permissões de privilégio mínimo.

  • Para crie um AccessKey de usuário RAM, acesse Create an AccessKey. O AccessKey ID e o Secret aparecem apenas no momento da criação. Salve-os imediatamente. Se perdidos, crie um novo par.

Configuração de variáveis de ambiente

Linux/macOS

  1. Defina o AccessKey do usuário RAM como variáveis de ambiente:

    export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'
    export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'
  2. Verifique:

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"

PowerShell

[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Exemplo de código

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Load credentials from environment variables for authentication
    val credentialsProvider = EnvironmentVariableCredentialsProvider()

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Configuração de credenciais estáticas

Codifique as credenciais diretamente no código (apenas para testes).

Aviso

Não incorpore credenciais em aplicações de produção. Este método destina-se apenas a testes.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.StaticCredentialsProvider

suspend fun main() {
    // Create a static credentials provider, explicitly setting the access key
    // Replace with the AccessKey ID and AccessKey Secret of your RAM user
    val credentialsProvider = StaticCredentialsProvider(
        accessKeyId = "YOUR_ACCESS_KEY_ID",
        accessKeySecret = "YOUR_ACCESS_KEY_SECRET"
    )

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar credenciais temporárias STS

Para aplicações que precisam de acesso temporário e com escopo definido ao OSS, inicialize o provedor de credenciais com credenciais temporárias STS (AccessKey ID, AccessKey Secret e Security Token). Atualize o token manualmente antes da expiração.

  • Os tokens STS expiram no momento especificado durante a geração e não podem ser usados posteriormente.

Configuração de variáveis de ambiente

Importante
  • Estas são credenciais temporárias STS (AccessKey ID, AccessKey Secret e Security Token), não o par de AccessKey de um usuário RAM.

  • O AccessKey ID do STS começa com "STS", por exemplo, "STS.L4aBSCSJVMuKg5U1****".

Linux/macOS

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>

Exemplo de código

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider

suspend fun main() {
    // Load the authentication information required to access OSS from environment variables, used for authentication
    val credentialsProvider = EnvironmentVariableCredentialsProvider()

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Configuração de credenciais estáticas

Codifique as credenciais temporárias diretamente no código (apenas para testes).

Aviso

Não incorpore credenciais em aplicações de produção. Este método destina-se apenas a testes.

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.StaticCredentialsProvider

suspend fun main() {
    // Enter the obtained temporary AccessKey ID and AccessKey Secret
    // Note that the Access Key ID obtained from the STS service starts with STS
    val stsAccessKeyId = "STS.****************"
    val stsAccessKeySecret = "yourAccessKeySecret"
    val stsSecurityToken = "yourSecurityToken"

    // Create a static credentials provider, explicitly setting the temporary access key and STS security token
    val credentialsProvider = StaticCredentialsProvider(
        accessKeyId = stsAccessKeyId,
        accessKeySecret = stsAccessKeySecret,
        securityToken = stsSecurityToken
    )

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar credenciais personalizadas

Se os tipos de credenciais nativos não atenderem às necessidades, implemente a interface CredentialsProvider para crie um provedor de credenciais personalizado.

Implementar a interface CredentialsProvider

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.Credentials
import com.aliyun.kotlin.sdk.service.oss2.credentials.CredentialsProvider

class CustomCredentialsProvider : CredentialsProvider {
    
    override suspend fun getCredentials(): Credentials {
        // TODO: implement your custom credential retrieval logic
        
        // Return long-term credentials
        return Credentials("access_key_id", "access_key_secret")
        
        // Return STS temporary credentials (if needed)
        // For temporary credentials, refresh them based on the expiration time
        // return Credentials("sts_access_key_id", "sts_access_key_secret", "security_token")
    }
}

suspend fun main() {
    // Create a custom credentials provider
    val credentialsProvider = CustomCredentialsProvider()

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Usar RefreshCredentialsProvider para atualização automática

Envolva o provedor de credenciais com RefreshCredentialsProvider para atualização automática:

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.CredentialsProvider
import com.aliyun.kotlin.sdk.service.oss2.credentials.RefreshCredentialsProvider
import kotlin.time.Duration.Companion.seconds

suspend fun main() {
    // Your original credentials provider
    val baseProvider: CredentialsProvider = CustomCredentialsProvider()
    
    // Wrap with RefreshCredentialsProvider to automatically refresh credentials
    // The default refresh interval is 300 seconds
    val credentialsProvider = RefreshCredentialsProvider(
        provider = baseProvider,
        refreshInterval = 300.seconds
    )

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
    }
}

Acesso anônimo

Acesse recursos do OSS com permissão de leitura pública sem credenciais:

import com.aliyun.kotlin.sdk.service.oss2.ClientConfiguration
import com.aliyun.kotlin.sdk.service.oss2.OSSClient
import com.aliyun.kotlin.sdk.service.oss2.credentials.AnonymousCredentialsProvider

suspend fun main() {
    // Create an anonymous credentials provider
    val credentialsProvider = AnonymousCredentialsProvider()

    val config = ClientConfiguration.loadDefault().apply {
        this.region = "cn-hangzhou"  // Specify the region where the bucket is located
        this.credentialsProvider = credentialsProvider
    }

    OSSClient.create(config).use { client ->
        // Use the created client for subsequent operations...
        // Note: anonymous access can only access resources that have public-read permission
    }
}

Execute exemplos

Execute exemplos CLI

# Build the project 
./gradlew :sample:cli:build

# Enter the sample program directory 
cd sample/cli/build/libs/

# Configure access credentials via environment variables
export OSS_ACCESS_KEY_ID="your access key id"
export OSS_ACCESS_KEY_SECRET="your access key secret"

# Using ListBuckets as an example
java -jar cli-jvm.jar ListBuckets --region cn-hangzhou

Execute exemplos de UI

> - Run `sample.composeApp` or `sample[jvm]`
> - Enter `AccessKeyId`, `AccessKeySecret`, and `Region`
> - Click `Set Client` to complete client initialization
> - Using ListObjects as an example, enter the bucket name and click `ListObjects`

Exemplos de código

Categoria

Descrição

Código de exemplo

Bucket

Crie um bucket

PutBucket.kt

Listar buckets

ListBuckets.kt

Obter informações do bucket

GetBucketInfo.kt

Obter localização do bucket

GetBucketLocation.kt

Obter estatísticas de armazenamento do bucket

GetBucketStat.kt

Exclua um bucket

DeleteBucket.kt

Verifique se um bucket existe

IsBucketExist.kt

Upload

Upload simples

PutObject.kt

Upload por anexação

AppendObject.kt

Upload multipartido - Iniciar

InitiateMultipartUpload.kt

Upload multipartido - Enviar parte

UploadPart.kt

Upload multipartido - Concluir

CompleteMultipartUpload.kt

Listar uploads multipartidos

ListMultipartUploads.kt

Listar partes enviadas

ListParts.kt

Abortar upload multipartido

AbortMultipartUpload.kt

Baixe

Baixe simples

GetObject.kt

Baixar para um arquivo local

GetObjectToFile.kt

Gerenciamento de objetos

Copiar um objeto

CopyObject.kt

Verifique se um objeto existe (HeadObject)

HeadObject.kt

Verifique se um objeto existe (IsObjectExist)

IsObjectExist.kt

Listar objetos

ListObjects.kt

Listar objetos V2

ListObjectsV2.kt

Exclua um objeto

DeleteObject.kt

Exclua múltiplos objetos

DeleteMultipleObjects.kt

Obter metadados do objeto

GetObjectMeta.kt

Arquivamento

Restaurar um objeto

RestoreObject.kt

Link simbólico

Crie um link simbólico

PutSymlink.kt

Obter um link simbólico

GetSymlink.kt

Tags de objeto

Defina tags de objeto

PutObjectTagging.kt

Obter tags de objeto

GetObjectTagging.kt

Exclua tags de objeto

DeleteObjectTagging.kt

Controle de acesso

Defina ACL do bucket

PutBucketAcl.kt

Obter ACL do bucket

GetBucketAcl.kt

Defina ACL do objeto

PutObjectAcl.kt

Obter ACL do objeto

GetObjectAcl.kt

Versionamento

Defina versionamento

PutBucketVersioning.kt

Obter status do versionamento

GetBucketVersioning.kt

Pré-assinatura

Gerar uma url pré-assinada

Presign.kt

Sistema

Consultar informações de endpoint

DescribeRegions.kt