All Products
Search
Document Center

Object Storage Service:OSS Kotlin SDK V2 (Preview)

Last Updated:Jun 09, 2026

Integrate Alibaba Cloud OSS into your Kotlin and Android applications with OSS Kotlin SDK V2 for file upload, download, and management.

GitHub | OSS Kotlin SDK V2 Developer Guide

Quick start

Get started with OSS Kotlin SDK V2:

image

Prerequisites

  • Kotlin: 2.1.0 or later

  • Java: Java 8+ at runtime (Java 11+ to build from source)

  • Supported platforms: Android, Desktop (JVM)

Verify the Kotlin version in your build.gradle.kts file. Upgrade if the version is earlier than 2.1.0.

Install the SDK

Install OSS Kotlin SDK V2 with Gradle (recommended).

Option 1: Gradle dependency (recommended)

Add the dependency to 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")
}

Packages:

  • kotlin-oss-v2: Core APIs for bucket operations, object operations, and advanced features (paginators, presigning)

  • kotlin-oss-v2-extension: Extension APIs for configuration features such as CORS

Option 2: Build from source

Clone the latest OSS Kotlin SDK V2 from GitHub and build with 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

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>")

Option 3: Manual dependency import

# 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 access credentials

Store a RAM user's AccessKey pair as environment variables.

Create a RAM user with permanent AccessKey access in the RAM console, save the AccessKey pair, and grant AliyunOSSFullAccess to the user.

Linux

  1. Append the environment variables to ~/.bashrc.

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Apply the changes.

    source ~/.bashrc
  3. Verify the environment variables.

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Check your default shell.

    echo $SHELL
  2. Proceed based on your default shell.

    Zsh

    1. Append the environment variables to ~/.zshrc.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Apply the changes.

      source ~/.zshrc
    3. Verify the environment variables.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    Bash

    1. Append the environment variables to ~/.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. Apply the changes.

      source ~/.bash_profile
    3. Verify the environment variables.

      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. Verify the environment variables.

    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. Verify the environment variables.

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

Initialize the client

Initialize OSSClient with Regions and Endpoints.

  • OSSClient implements Closeable. When used with the use extension function, resources are released automatically without calling close.

  • Creating and destroying OSSClient is expensive. Reuse a singleton instance, and call close before your application exits to avoid resource leaks.

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}")
            }
        }
    }
}

Output lists all buckets across regions in your account:

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

Description

region

(Required) The region to send requests to

credentialsProvider

(Required) The credentials provider

endpoint

The endpoint URL

httpTransport

The HTTP transport layer

retryMaxAttempts

Maximum number of HTTP request attempts. Default: 3

retryer

The retry implementation for HTTP requests

connectTimeout

Connection timeout. Default: 10 seconds

readWriteTimeout

Read/write timeout. Default: 20 seconds

insecureSkipVerify

Whether to skip SSL certificate verification. Default: false

enabledRedirect

Whether to enable HTTP redirect. Default: false

proxyHost

The proxy server

signatureVersion

Signature version. Default: v4

disableSsl

Whether to use HTTP instead of HTTPS. Default: false (HTTPS)

usePathStyle

Whether to use path-style URLs. Default: virtual-hosted style

useCName

Whether to use a custom domain name. Default: false

useDualStackEndpoint

Whether to use a dual-stack endpoint. Default: false

useAccelerateEndpoint

Whether to use a transfer acceleration endpoint. Default: false

useInternalEndpoint

Whether to use an internal endpoint. Default: false

additionalHeaders

Additional headers to sign. Valid only with V4 signatures

userAgent

Additional User-Agent information

disableUploadCRC64Check

Whether to disable upload CRC64 verification. Default: enabled

disableDownloadCRC64Check

Whether to disable download CRC64 verification. Default: enabled

Use a custom domain name

A custom domain name enables direct browser preview and CDN acceleration for OSS-hosted files.

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...
    }
}

Timeout settings

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...
    }
}

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:
     *
     * 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...
    }
}

HTTP/HTTPS protocol

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()
        // Disable HTTPS requests
        disableSsl = true
    }

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

Use an internal endpoint

Use the internal network to access OSS resources in the same region, reducing traffic costs and improving performance.

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...
    }
}

Use transfer 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() {
    // 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...
    }
}

Use a dedicated 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 for subsequent operations...
    }
}

Use a China Government Cloud endpoint

Configure OSSClient with a Regions and Endpoints 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() {
    // 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...
    }
}

Access credential configuration

OSS Kotlin SDK V2 supports multiple credential types. Choose one based on your security and access requirements.

How do I choose a credential type?

Credential type

Scenario

Kotlin SDK V2 support

Underlying credential

Validity

Rotation or refresh

Use the AccessKey of a RAM user

Secure, stable environments requiring long-term access without frequent credential rotation

Built-in

AK

Long-term

Manual rotation

Use STS temporary credentials

Untrusted environments requiring controlled access duration and permissions

Built-in

STS Token

Temporary

Manual refresh

Use custom credentials

When none of the above credential types meet your needs

Built-in

Custom

Custom

Custom

Anonymous access

Access public-read resources without credentials

Built-in

N/A

N/A

N/A

Use the AccessKey of a RAM user

For applications in secure, stable environments that need long-term OSS access, initialize the credentials provider with a RAM user's AccessKey pair (AccessKey ID and AccessKey Secret). This requires manual key management and rotation.

Important
  • An Alibaba Cloud account has full access to all resources. A leaked AccessKey poses significant security risk. Use a RAM user AccessKey with least-privilege permissions instead.

  • To create a RAM user AccessKey, go to Create an AccessKey. The AccessKey ID and Secret are shown only at creation. Save them immediately — if lost, create a new pair.

Environment variable configuration

Linux/macOS

  1. Set the RAM user AccessKey as environment variables:

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

    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 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...
    }
}

Static credential configuration

Hard-code credentials directly (testing only).

Warning

Do not embed credentials in production applications. 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 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...
    }
}

Use STS temporary credentials

For applications that need temporary, scoped OSS access, initialize the credentials provider with STS temporary credentials (AccessKey ID, AccessKey Secret, and Security Token). You must refresh the token manually before expiration.

  • STS tokens expire at the time specified during generation and cannot be used afterward.

Environment variable configuration

Important
  • These are STS temporary credentials (AccessKey ID, AccessKey Secret, and Security Token), not a RAM user's AccessKey pair.

  • The AccessKey ID 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, 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...
    }
}

Static credential configuration

Hard-code temporary credentials directly (testing only).

Warning

Do not embed credentials in production applications. 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() {
    // 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...
    }
}

Use custom credentials

If built-in credential types do not meet your needs, implement the CredentialsProvider interface to create a custom credentials provider.

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 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...
    }
}

Use RefreshCredentialsProvider for automatic refresh

Wrap your credentials provider with RefreshCredentialsProvider for automatic refresh:

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...
    }
}

Anonymous access

Access public-read OSS resources without 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 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
    }
}

Run examples

Run CLI examples

# 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 secrect"

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

Run UI examples

> - 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`

Code samples

Category

Description

Sample code

Bucket

Create a bucket

PutBucket.kt

List buckets

ListBuckets.kt

Get bucket info

GetBucketInfo.kt

Get bucket location

GetBucketLocation.kt

Get bucket storage statistics

GetBucketStat.kt

Delete a bucket

DeleteBucket.kt

Check if a bucket exists

IsBucketExist.kt

Upload

Simple upload

PutObject.kt

Append upload

AppendObject.kt

Multipart upload - Initiate

InitiateMultipartUpload.kt

Multipart upload - Upload part

UploadPart.kt

Multipart upload - Complete

CompleteMultipartUpload.kt

List multipart uploads

ListMultipartUploads.kt

List uploaded parts

ListParts.kt

Abort multipart upload

AbortMultipartUpload.kt

Download

Simple download

GetObject.kt

Download to a local file

GetObjectToFile.kt

Object management

Copy an object

CopyObject.kt

Check if an object exists (HeadObject)

HeadObject.kt

Check if an object exists (IsObjectExist)

IsObjectExist.kt

List objects

ListObjects.kt

List objects V2

ListObjectsV2.kt

Delete an object

DeleteObject.kt

Delete multiple objects

DeleteMultipleObjects.kt

Get object metadata

GetObjectMeta.kt

Archive

Restore an object

RestoreObject.kt

Symbolic link

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 bucket ACL

PutBucketAcl.kt

Get bucket ACL

GetBucketAcl.kt

Set object ACL

PutObjectAcl.kt

Get object ACL

GetObjectAcl.kt

Versioning

Set versioning

PutBucketVersioning.kt

Get versioning status

GetBucketVersioning.kt

Presigning

Generate a presigned URL

Presign.kt

System

Query endpoint information

DescribeRegions.kt