All Products
Search
Document Center

Object Storage Service:OSS Kotlin SDK V2 (Preview)

Last Updated:Mar 03, 2026

Use the OSS Kotlin SDK V2 to integrate Alibaba Cloud Object Storage Service (OSS) into your Kotlin and Android applications. This lets you upload, download, and manage files. It is ideal for mobile apps and cross-platform developers who need to perform cloud file storage operations.

Github| OSS Kotlin SDK V2 Developer Guide

Quick integration

The process of integrating the OSS Kotlin SDK V2 is as follows:

image

Prepare the environment

  • Kotlin: Version 2.1.0 or later

  • Java: Java 8+ is required for the runtime. Java 11+ is required to build from source.

  • Supported platforms: Android, Desktop (JVM)

Check the Kotlin version in your project's build.gradle.kts file. If Kotlin is not installed or the version is too old, upgrade your Kotlin version.

Install the SDK

We recommend that you use Gradle to install the OSS Kotlin SDK V2.

Method 1: Gradle dependency (Recommended)

Add the dependency to the build.gradle.kts file:

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

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

Package description:

  • kotlin-oss-v2: Provides basic bucket interfaces, object-related interfaces, and advanced interfaces (paginators, presigning).

  • kotlin-oss-v2-extension: Contains configuration-related interfaces, such as the cross-origin resource sharing interface.

Method 2: Build from source

Obtain the latest version of the OSS Kotlin SDK V2 from GitHub, and then build and install it using Gradle:

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

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

# Publish to MavenLocal
$ ./gradlew clean publishToMavenLocal

Add mavenLocal to your repository configuration:

repositories {
    ...
    mavenLocal()
}

Add the dependency to your project.

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

Method 3: Manually import dependency packages

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

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

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

# Take aar as an example
# Go to the packaging output directory. The package is generated in this directory.
$ cd oss-sdk/build/outputs/aar && ls
# cd oss-sdk-extension/build/outputs/aar && ls

Configure access credentials

Set the AccessKey pair of a RAM user to environment variables as credentials.

In the RAM console, create a RAM user that uses a permanent AccessKey pair for access. Save the AccessKey pair, and then grant the AliyunOSSFullAccess permission to the user.

Linux

  1. Run the following commands in the command-line interface (CLI) to append the environment variable settings to the ~/.bashrc file.

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Run the following command for the changes to take effect.

    source ~/.bashrc
  3. Run the following commands to check if the environment variables are effective.

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Run the following command in the terminal to view the default shell type.

    echo $SHELL
  2. Perform operations based on the default shell type.

    Zsh

    1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Run the following command for the changes to take effect.

      source ~/.zshrc
    3. Run the following commands to check if the environment variables are effective.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    Bash

    1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

      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. Run the following command for the changes to take effect.

      source ~/.bash_profile
    3. Run the following commands to check if the environment variables are effective.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Run the following commands in CMD.

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Run the following commands to check if the environment variables are effective.

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. Run the following commands in 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. Run the following commands to check if the environment variables are effective.

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

Initialize the client

Initialize the OSSClient with a region and endpoint.

  • The OSSClient implements the Closeable interface. When you use the use extension function, resources are automatically released. You do not need to manually call close.

  • Because creating and destroying an OSSClient is time-consuming, use the singleton pattern to reuse the OSSClient instance. To prevent resource leaks, manually call close before the application stops.

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 default SDK configurations.
    // 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}")
            }
        }
    }
}

The output shows the buckets for the current account in all regions:

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

Client configuration

What configurations does the client support?

Parameter Name

Description

region

(Required) The region to which requests are sent.

credentialsProvider

(Required) Set access credentials.

endpoint

Endpoint

httpTransport

HTTP transport layer.

retryMaxAttempts

Maximum number of attempts for an HTTP request. Default is 3.

retryer

Retry implementation for HTTP requests.

connectTimeout

Connection timeout. Default is 10 seconds.

readWriteTimeout

Read/write data timeout. Default is 20 seconds.

insecureSkipVerify

Skip SSL certificate verification. SSL certificates are verified by default.

enabledRedirect

Enable HTTP redirection. Disabled by default.

proxyHost

Set a proxy server.

signatureVersion

Signature version. Default is v4.

disableSsl

You do not need to configure HTTPS requests because HTTPS is used by default.

usePathStyle

Use path-style requests (instead of virtual-hosted–style requests). Default uses bucket-hosted domains.

useCName

Use a custom domain name. Disabled by default.

useDualStackEndpoint

Use a dual-stack endpoint. Disabled by default.

useAccelerateEndpoint

Use an acceleration endpoint. Disabled by default.

useInternalEndpoint

Specifies whether to use an internal same-region endpoint for access. This option is disabled by default.

additionalHeaders

Specify additional signed request headers. Valid only with V4 signatures.

userAgent

Specify additional User-Agent information.

disableUploadCRC64Check

Disable CRC-64 check on uploads. Enabled by default.

disableDownloadCRC64Check

Disable CRC-64 check on downloads. Enabled by default.

Use a custom domain name

When you access OSS using the default domain name, you might encounter issues, such as blocked file access or the inability to preview files. However, accessing OSS through a custom domain name allows browsers to preview files directly and supports CDN acceleration.

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 your bucket is located. For example, use "cn-hangzhou" for China (Hangzhou).
    val region = "cn-hangzhou"
    
    // Enter your custom domain name. For example: www.example-***.com
    val endpoint = "https://www.example-***.com"

    val config = ClientConfiguration.loadDefault().apply {
        this.region = region
        this.endpoint = endpoint
        // Set useCName to true to enable CNAME. Otherwise, custom domains won't work.
        this.useCName = true
        credentialsProvider = EnvironmentVariableCredentialsProvider()
    }

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

Timeout control

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 connection timeout. Default is 10 seconds.
        connectTimeout = 30.seconds
        // Set read/write data timeout. Default is 20 seconds.
        readWriteTimeout = 30.seconds
    }

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

Retry policy

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 notes:
     *
     * Default retry policy:
     * If no retry policy is configured, the SDK uses StandardRetryer by default with these settings:
     * - maxAttempts: Maximum number of attempts. Default is 3.
     * - maxBackoff: Maximum backoff time. Default is 20 seconds.
     * - baseDelay: Base delay time. Default is 200 milliseconds.
     * - backoffDelayer: Backoff algorithm. Default uses FullJitter.
     *   Formula: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff)
     * - errorRetryable: Retryable error types, including HTTP status codes, service error codes, and client errors.
     *
     * When a retryable error occurs, the request is delayed and retried based on these settings.
     * Overall request delay increases with each retry attempt.
     * If the default settings don't meet your needs, configure retry parameters or change the retry implementation.
     */

    val region = "cn-hangzhou"

    // Example retry policy configurations:

    // 1. Customize maximum retry attempts (default is 3; set to 5 here)
    val customRetryer = StandardRetryer.newBuilder()
        .setMaxAttempts(5)
        .build()

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

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

    // 4. Disable retries entirely
    // Use NopRetryer to disable all retry attempts
    // val customRetryer = NopRetryer()

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

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

HTTP/HTTPS protocol

You can set disableSsl = true to use HTTP instead of 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()
        // Use HTTP instead of HTTPS
        disableSsl = true
    }

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

Use an internal same-region endpoint

Accessing OSS resources in the same region using an internal same-region endpoint reduces traffic costs and improves access speed.

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() {
    // Method 1: Specify the region and set useInternalEndpoint to true
    val region = "cn-hangzhou"

    // Method 2: Directly specify the region and endpoint
    // 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 using Method 2, uncomment the next line and comment out the previous line
        // this.endpoint = endpoint
    }

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

Use an acceleration endpoint

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() {
    // Method 1: Specify the region and set useAccelerateEndpoint to true
    val region = "cn-hangzhou"

    // Method 2: Directly specify the region and acceleration endpoint
    // val region = "cn-hangzhou"
    // val endpoint = "https://oss-accelerate.aliyuncs.com"

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

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

Use a private domain

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 to perform subsequent operations...
    }
}

Use Gov Cloud endpoints

The following example shows how to configure OSSClient using Alibaba Gov Cloud 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 your bucket is located. For Alibaba Gov Cloud 1 in China North 2, use "cn-north-2-gov-1".
    val region = "cn-north-2-gov-1"
    
    // Specify the internal endpoint for the region. For Alibaba Gov Cloud 1 in China North 2:
    // To use HTTP, set the endpoint to '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 to perform subsequent operations...
    }
}

Configure access credentials

The Alibaba Cloud Object Storage Service (OSS) Kotlin software development kit (SDK) V2 offers multiple methods for configuring access credentials. You can select an initialization method based on your authentication and authorization requirements.

How to choose access credentials

Credential provider initialization method

Scenarios

Kotlin SDK V2 support

Underlying credential

Credential validity

Credential rotation or refresh method

Use the AccessKey of a RAM user

For applications that are deployed in a secure and stable environment not vulnerable to external attacks. These applications require long-term access to Alibaba Cloud services without frequent credential rotation.

Built-in support

AccessKey

Long-term

Manual rotation

Use an STS temporary access credential

For applications that are deployed in an untrusted environment. You want to control the validity period and permissions for access.

Built-in support

STS token

Temporary

Manual refresh

Use a custom access credential

If the preceding credential configuration methods do not meet your requirements, you can customize how credentials are obtained.

Built-in support

Custom

Custom

Custom

Anonymous access

To access public-read OSS resources without providing any credentials.

Built-in support

None

None

None

Use the AccessKey of a RAM user

If your application is deployed in a secure and stable environment, requires long-term access to OSS, and does not support frequent credential rotation, you can initialize the credential provider with the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a Resource Access Management (RAM) user. This method requires you to manually maintain the AccessKey pair, which increases security risks and maintenance complexity.

Important
  • An Alibaba Cloud account has full permissions for all resources. If an AccessKey pair is leaked, it poses a significant security risk to your system. We recommend that you do not use the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.

  • For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only at the time of creation. You must save them immediately. If you lose the AccessKey pair, you must create a new one.

Configure environment variables

Linux/macOS

  1. Configure the environment variables with the AccessKey pair of the RAM user:

    export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'
    export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'
  2. Run the following commands to verify that the environment variables are configured:

    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)

Code example

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 credential information from environment variables for identity verification.
    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...
    }
}

Configure static credentials

The following code example shows how to hard-code access credentials and explicitly specify the AccessKey pair to use.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing only.

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 credential provider and explicitly set the AccessKey pair.
    // 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...
    }
}

Use an STS temporary access credential

If your application needs temporary access to OSS, you can initialize the credential provider with a temporary identity credential (AccessKey ID, AccessKey secret, and Security Token Service token) obtained from the Security Token Service (STS). This method requires you to manually maintain the STS token, which increases security risks and maintenance complexity. Additionally, to access OSS multiple times, you must manually refresh the STS token.

  • You must specify a time-to-live (TTL) when you generate an STS token. The token automatically expires after the specified TTL.

Configure environment variables

Important
  • This method uses the temporary identity credential (AccessKey ID, AccessKey secret, and Security Token Service token) obtained from STS, not the AccessKey pair of a RAM user.

  • An AccessKey ID obtained from STS starts with "STS.", for example, "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>

Code example

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 for identity verification.
    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...
    }
}

Configure static credentials

The following code example shows how to hard-code access credentials and explicitly specify the temporary AccessKey pair to use.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing only.

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() {
    // Specify the temporary AccessKey ID and AccessKey secret.
    // Note that an AccessKey ID obtained from STS starts with "STS."
    val stsAccessKeyId = "STS.****************"
    val stsAccessKeySecret = "yourAccessKeySecret"
    val stsSecurityToken = "yourSecurityToken"

    // Create a static credential provider and explicitly set the temporary AccessKey pair 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...
    }
}

Use a custom access credential

If the preceding methods for configuring credentials do not meet your requirements, you can customize how credentials are provided. The Kotlin SDK lets you customize the credential provider by implementing the CredentialsProvider interface.

Implement the CredentialsProvider interface

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 logic for obtaining credentials.
        
        // Return a long-term credential.
        return Credentials("access_key_id", "access_key_secret")
        
        // Return an STS temporary credential if needed.
        // For temporary credentials, you must refresh them based on their expiration time.
        // return Credentials("sts_access_key_id", "sts_access_key_secret", "security_token")
    }
}

suspend fun main() {
    // Create a custom credential 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...
    }
}

Use RefreshCredentialsProvider to auto-refresh credentials

To auto-refresh credentials, you can wrap your credential provider with RefreshCredentialsProvider:

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 credential provider.
    val baseProvider: CredentialsProvider = CustomCredentialsProvider()
    
    // Wrap with RefreshCredentialsProvider to auto-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...
    }
}

Anonymous access

If you only need to access public-read OSS resources, you can use anonymous access without providing any credentials.

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 credential 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 be used to access public-read resources.
    }
}

Run examples

Run the CLI example

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

# Go to the sample program folder 
cd sample/cli/build/libs/

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

# Example: ListBuckets
java -jar cli-jvm.jar ListBuckets --region cn-hangzhou

Run the UI example

> - Run `sample.composeApp` or `sample[jvm]`.
> - Enter the `AccessKeyId`, `AccessKeySecret`, and `Region`.
> - Click `Set Client` to initialize the client.
> - For example, to list objects, enter a bucket name and click `ListObjects`.

Sample code

Feature categorization

Example description

Sample code

Buckets

Create a bucket

PutBucket.kt

List buckets

ListBuckets.kt

Retrieve Bucket Information

GetBucketInfo.kt

Get the region of a bucket

GetBucketLocation.kt

Retrieve storage capacity statistics

GetBucketStat.kt

Delete a bucket

DeleteBucket.kt

Check whether a bucket exists

IsBucketExist.kt

File Upload

Simple upload

PutObject.kt

Append upload

AppendObject.kt

Multipart upload: Initialization

InitiateMultipartUpload.kt

Multipart upload: Upload a part

UploadPart.kt

Multipart upload: Complete an upload

CompleteMultipartUpload.kt

List multipart upload tasks

ListMultipartUploads.kt

List uploaded parts

ListParts.kt

Cancel a multipart upload

AbortMultipartUpload.kt

File Download

Simple download

GetObject.kt

Download an object to a local file

GetObjectToFile.kt

File Management

Copy Files

CopyObject.kt

Check whether an object exists

HeadObject.kt

Check whether an object exists

IsObjectExist.kt

List the files.

ListObjects.kt

List objects V2

ListObjectsV2.kt

Delete a file

DeleteObject.kt

Delete multiple objects

DeleteMultipleObjects.kt

Get object metadata

GetObjectMeta.kt

Archived object

Restore Files

RestoreObject.kt

Symbolic links

Create a symbolic link

PutSymlink.kt

Get a symbolic link

GetSymlink.kt

Object tagging

Set object tags

PutObjectTagging.kt

Get object tags

GetObjectTagging.kt

Delete object tags

DeleteObjectTagging.kt

Access control

Set the ACL of a bucket

PutBucketAcl.kt

Get the ACL of a bucket

GetBucketAcl.kt

Set the ACL of an object

PutObjectAcl.kt

Get the ACL of an object

GetObjectAcl.kt

Versioning

Set versioning

PutBucketVersioning.kt

Get the versioning status

GetBucketVersioning.kt

Presigned URL

Generate a presigned URL

Presign.kt

System feature

Query Endpoint information

DescribeRegions.kt