All Products
Search
Document Center

Object Storage Service:OSS Java SDK V2

Last Updated:Mar 26, 2026

The OSS SDK for Java 2.0 enables Java applications to upload, download, and manage files on Alibaba Cloud Object Storage Service (OSS). It is designed for developers building websites and enterprise applications that rely on cloud-based file storage.

GitHub | OSS SDK for Java API | mvnrepository | deepwiki

Quick start

Follow these steps to use the OSS Java SDK V2.

image

Prerequisites

Java 8 or later.

Run the java -version command to check your Java version. If you do not have Java 8 or later installed, download and install Java.

Install SDK

We recommend installing the OSS Java SDK V2 with Maven.

Maven

Add the following dependency to your pom.xml file. Replace <version> with the latest version number from the Maven Repository.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-oss-v2</artifactId>
    <version><!-- Specify the latest version number--></version>
</dependency>

Source code

Get the latest version of the OSS Java SDK V2 from GitHub, and then build and install it using Maven:

mvn clean install -DskipTests -Dgpg.skip=true

Configure access credentials

Store a RAM user's AccessKey in an environment variable to serve as your access credentials.

In the RAM console, create a RAM user with Permanent AccessKey Pair access. Save the AccessKey pair, and then grant the AliyunOSSFullAccess permission to the user.

Linux

  1. Run the following commands 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
    1. Run the following command to apply the changes.

      source ~/.bashrc
    2. Run the following commands to verify that the environment variables are configured.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Run the following command in the terminal to check your default shell.

    echo $SHELL
    1. Follow the steps for your 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 to apply the changes.

        source ~/.zshrc
      3. Run the following commands to verify that the environment variables are configured.

        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 to apply the changes.

        source ~/.bash_profile
      3. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Run the following commands in Command Prompt.

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    1. Run the following commands to verify that the environment variables are configured.

      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)
    1. Run the following commands to verify that the environment variables are configured.

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

Initialize client

Important

Due to a policy change to improve compliance and security, starting March 20, 2025, new OSS users must use a custom domain name (CNAME) to perform data API operations on OSS buckets located in Chinese mainland regions. Default public endpoints are restricted for these operations. Refer to the official announcement for a complete list of the affected operations. If you access your data via HTTPS, you must bind a valid SSL Certificate to your custom domain. This is mandatory for OSS Console access, as the console enforces HTTPS.

  • The OSSClient implements AutoCloseable. When you create an instance by using a try-with-resources statement, resources are automatically released. You do not need to manually call the close() method.

  • We recommend using the singleton pattern to reuse an OSSClient instance. To prevent resource leaks when using this pattern, you must manually call the close() method before the application terminates.

    Singleton pattern

    Before you run the sample code, replace <region-id> with an actual region ID, such as or ap-southeast-1.
    public class OssClientSingleton {
        private OssClientSingleton() {}
    
        private static class Holder {
            private static final OSSClient INSTANCE = OSSClient.newBuilder()
                .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                .region("<region-id>")
                .build();
        }
    
        public static OSSClient getInstance() {
            return Holder.INSTANCE;
        }
    
        // Shuts down the OSSClient. This must be called explicitly.
        public static void shutdown() {
            try {
                getInstance().close();
            } catch (Exception e) {
                // Handle the close exception.
            }
        }
    }
    

Synchronous OSSClient

If you want to wait for an operation to complete before proceeding, use the synchronous OSSClient.

Before you run the sample code, replace <region-id> with an actual region ID, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;
import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable;

public class Example {
    public static void main(String[] args) {
        String region = "<region-id>";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {

            ListBucketsIterable paginator = client.listBucketsPaginator(
                    ListBucketsRequest.newBuilder()
                            .build());

            for (ListBucketsResult result : paginator) {
                for (BucketSummary info : result.buckets()) {
                    System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n", info.name(), info.region(), info.storageClass());
                }
            }

        } catch (Exception e) {
//            ServiceException se = ServiceException.asCause(e);
//            if (se != null) {
//                System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode());
//            }
            System.out.printf("error:\n%s", e);
        }
    }
}

Asynchronous OSSClient

If you need to process multiple OSS operations concurrently and do not depend on the result of each operation, use the asynchronous OSSClient.

Before you run the sample code, replace <region-id> with an actual region ID, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSAsyncClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;

import java.util.concurrent.CompletableFuture;

public class ExampleAsync {
    public static void main(String[] args) {
        String region = "<region-id>";
        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();

        try (OSSAsyncClient client = OSSAsyncClient.newBuilder()
                .region(region)
                .credentialsProvider(provider)
                .build()) {

            CompletableFuture<ListBucketsResult> future = client.listBucketsAsync(
                    ListBucketsRequest.newBuilder().build()
            );

            future.thenAccept(result -> {
                        for (BucketSummary info : result.buckets()) {
                            System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n",
                                    info.name(), info.region(), info.storageClass());
                        }
                    })
                    .exceptionally(e -> {
//                ServiceException se = ServiceException.asCause(e);
//                if (se != null) {
//                    System.out.printf("Async ServiceException: requestId:%s, errorCode:%s\n",
//                            se.requestId(), se.errorCode());
//                }
                        System.out.printf("async error:\n%s\n", e);
                        return null;
                    });

            future.join();

        } catch (Exception e) {
            System.out.printf("main error:\n%s\n", e);
        }
    }
}

After you run the code, the output lists the buckets in all regions associated with your account.

Client configuration

Supported client configurations

Parameter

Description

region

(Required) The region to send the request to.

credentialsProvider

(Required) The credentials for authentication.

endpoint

The request endpoint.

httpClient

The HTTP client.

retryMaxAttempts

The maximum number of retry attempts for an HTTP request. Defaults to 3.

retryer

The retry policy for HTTP requests.

connectTimeout

The connection timeout. Defaults to 5 seconds.

readWriteTimeout

The read/write timeout. Defaults to 20 seconds.

insecureSkipVerify

Whether to skip SSL certificate verification. Defaults to false.

enabledRedirect

Whether to enable HTTP redirection. Defaults to false.

signatureVersion

The signature version. Defaults to v4.

disableSsl

Whether to disable HTTPS. Defaults to false.

usePathStyle

Whether to use path-style access (for example, https://endpoint/bucket-name). Defaults to false, which uses virtual-hosted style access (for example, https://bucket-name.endpoint).

useCName

Whether to use a custom domain name for access. Defaults to false.

useDualStackEndpoint

Whether to use a dual-stack endpoint for access. Defaults to false.

useAccelerateEndpoint

Whether to use a transfer acceleration endpoint for access. Defaults to false.

useInternalEndpoint

Whether to use an internal endpoint for access. Defaults to false.

additionalHeaders

Additional request headers to include in the v4 signature.

userAgent

A custom string to append to the User-Agent header.

Custom domain name

Using a default OSS endpoint can prevent you from accessing or previewing files. To resolve this, you can use a custom domain name to access OSS. This also lets you preview files directly in a browser and use a CDN for accelerated content delivery.

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Specify your custom domain name. For example, www.example-***.com.
        String endpoint = "https://www.example-***.com";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                // Note: Set useCName to true. Otherwise, you cannot use the custom domain name.
                .useCName(true)
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Timeouts

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Set the connection timeout. The default is 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Set the read/write timeout. The default is 20 seconds.
                .readWriteTimeout(Duration.ofSeconds(30))
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Retry policy

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.retry.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        /*
         * SDK retry policy configuration:
         *
         * Default retry policy:
         * If no retry policy is configured, the SDK uses StandardRetryer as the default client implementation.
         * The default settings are as follows:
         * - maxAttempts: The maximum number of retry attempts. The default is 3.
         * - maxBackoff: The maximum backoff time. The default is 20 seconds.
         * - baseDelay: The base delay for retries. The default is 0.2 seconds.
         * - backoffDelayer: The backoff algorithm. The default is FullJitter. The formula is: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff).
         * - errorRetryables: The types of retryable errors, including specific HTTP status codes, service error codes, and client errors.
         *
         * When a retryable error occurs, the SDK uses these settings to delay and then retry the request.
         * Latency increases with each retry. If the defaults do not meet your needs,
         * you can customize the retry parameters or implementation.
         */

        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Example of configuring a retry policy:

        // 1. Customize the maximum number of retries. The default is 3. This example sets the value to 5.
        Retryer customRetryer = StandardRetryer.newBuilder()
                .maxAttempts(5)
                .build();

        // 2. Customize the backoff delay time.
        // Set the baseDelay to 0.5 seconds (default: 0.2 seconds) and maxBackoff to 25 seconds (default: 20 seconds).
        // Retryer customRetryer = StandardRetryer.newBuilder()
        //         .backoffDelayer(new FullJitterBackoff(Duration.ofMillis(500), Duration.ofSeconds(25)))
        //         .build();

        // 3. Customize the backoff algorithm.
        // Use a fixed-delay backoff algorithm instead of the default FullJitter. This example sets a 2-second delay for each retry.
        // Retryer customRetryer = StandardRetryer.newBuilder()
        //         .backoffDelayer(new FixedDelayBackoff(Duration.ofSeconds(2)))
        //         .build();

        // 4. Disable the retry policy.
        // Use NopRetryer to disable all retry attempts.
        // Retryer customRetryer = new NopRetryer();

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .retryer(customRetryer)
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

HTTP/HTTPS

To use HTTP instead of HTTPS, call disableSsl(true).

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Disable HTTPS requests.
                .disableSsl(true)
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Internal endpoint

You can use an internal endpoint to access OSS resources from an Alibaba Cloud service in the same region. This reduces traffic costs and improves access speed.

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Method 1: Specify the region and set useInternalEndpoint to true.
        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // // Method 2: Specify both the region and the internal endpoint.
        // // Specify the region where the bucket is located.
        // String region = "<region-id>";
        // // Specify the internal endpoint for the bucket's region.
        // String endpoint = "<endpoint>";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useInternalEndpoint(true)
                // .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the `useInternalEndpoint(true)` line above.
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Transfer acceleration endpoint

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Method 1: Specify the region and set useAccelerateEndpoint to true.
        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // // Method 2: Specify both the region and the transfer acceleration endpoint.
        // // Specify the region where the bucket is located.
        // String region = "<region-id>";
        // // Specify the transfer acceleration endpoint for the bucket's region, for example, 'https://oss-accelerate.aliyuncs.com'.
        // String endpoint = "https://oss-accelerate.aliyuncs.com";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useAccelerateEndpoint(true)
                // .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the `useAccelerateEndpoint(true)` line above.
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Private domain

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Specify your private domain, for example, https://service.corp.example.com.
        String endpoint = "https://service.corp.example.com";

        // Create an OSS client with the specified configurations.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                .build()) {

            // Use the client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Custom HTTP client

If standard configurations are insufficient, you can use a custom HTTP client.

Before running the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
Note

The following example shows the custom HTTPClient configuration for the synchronous client (OSSClient). If you use the asynchronous client (OSSAsyncClient), replace Apache5HttpClientBuilder with Apache5AsyncHttpClientBuilder. The other configuration parameters are the same.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.transport.HttpClient;
import com.aliyun.sdk.service.oss2.transport.HttpClientOptions;
import com.aliyun.sdk.service.oss2.transport.apache5client.Apache5HttpClientBuilder;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        // Load credentials from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located.
        String region = "<region-id>";

        // Set the parameters for the HTTP client.
        HttpClientOptions httpClientOptions = HttpClientOptions.custom()
                // Connection timeout. The default value is 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Read/write timeout. The default value is 20 seconds.
                .readWriteTimeout(Duration.ofSeconds(30))
                // Maximum number of connections. The default value is 1024.
                .maxConnections(2048)
                // Specifies whether to skip certificate verification. Default value: false.
                .insecureSkipVerify(false)
                // Specifies whether to enable HTTP redirection. Default value: false.
                .redirectsEnabled(false)
                // Set the proxy server.
                // .proxyHost("http://user:passswd@proxy.example-***.com")
                .build();

        // Create an HTTP client and pass the HTTP client parameters.
        HttpClient httpClient = Apache5HttpClientBuilder.create()
                .options(httpClientOptions)
                .build();

        // Create an OSS client by using the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .httpClient(httpClient)
                .build()) {

            // Use the created client to perform subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Access credentials

The OSS SDK for Java V2 provides multiple ways to configure access credentials. Choose a suitable initialization method based on your authentication and authorization needs.

Choose an access credential

Initialization method

Scenario

Java SDK V2 support

Underlying credential

Validity

Rotation and refresh

Use the AccessKey pair of a RAM user

For applications that run in a secure environment and require long-term access to cloud services without frequent credential rotation.

Built-in support

AccessKey pair

Long-term

Manual rotation

Use an STS token

For applications running in an untrusted environment that require control over access validity and permissions.

Built-in support

STS token

Temporary

Manual refresh

Use RAM role ARN credentials

For cross-account access to OSS resources that require temporary credentials obtained by assuming a RAM role.

Extended support

STS token

Temporary

Automatic refresh

Use ECS RAM role credentials

For applications running on an ECS instance, an ECI instance, or a Container Service for Kubernetes cluster.

Extended support

STS token

Temporary

Automatic refresh

Use OIDC role ARN credentials

For using the RAM Roles for Service Accounts (RRSA) feature in Container Service for Kubernetes to achieve Pod-level permission isolation.

Extended support

STS token

Temporary

Automatic refresh

Use a custom credential provider

When none of the preceding methods meet your requirements, you can implement a custom way to obtain credentials.

Built-in support

Custom

Custom

Custom

Anonymous access

Access public-read OSS resources without providing any credentials.

Built-in support

None

None

None

Features marked as Extended support require using the custom access credential method with the Alibaba Cloud credentials management library. The SDK provides built-in support for basic credential configurations. You can implement extended features by integrating the credentials-java library.

Use a RAM user's AccessKey pair

If your application runs in a secure environment that requires long-term access to OSS without frequent credential rotation, you can initialize the credential provider by using the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user. This method requires you to manually maintain an AccessKey pair, increasing security risks and maintenance complexity.

Important
  • An Alibaba Cloud account has full permissions over its resources. If the AccessKey pair of an Alibaba Cloud account is leaked, it poses a significant security risk to your system. We recommend using the AccessKey pair of a RAM user with the minimum required permissions.

  • To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret are displayed only when the pair is created. You must save them immediately. If you forget the AccessKey pair, create a new one to replace it.

Environment variables

Linux/macOS

  1. Set the environment variables using the RAM user's AccessKey pair:

    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 set:

    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 sample

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Load credential information from environment variables for authentication.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Static credentials

The following code shows how to hard-code an access credential by explicitly setting the AccessKey pair.

Warning

Do not hard-code an access credential in your production applications. This method is for testing purposes only.

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Create a static credential provider and explicitly set the AccessKey pair.
        // Replace with your RAM user's AccessKey ID and AccessKey secret.
        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
                "YOUR_ACCESS_KEY_ID",
                "YOUR_ACCESS_KEY_SECRET"
        );
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Use an STS token

If your application requires temporary access to OSS, you can use a temporary access credential (AccessKey ID, AccessKey secret, and security token) obtained from Security Token Service (STS) to initialize the credential provider. This method requires you to manually maintain an STS token, increasing security risks and maintenance complexity. If you need to make multiple temporary requests to OSS, you must manually refresh the STS token.

Environment variables

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

  • The 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 sample

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Load the authentication information required to access OSS from environment variables.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Static credentials

The following code shows how to hard-code an access credential by explicitly setting the temporary AccessKey pair and security token.

Warning

Do not hard-code an access credential in your production applications. This method is for testing purposes only.

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Specify the obtained temporary AccessKey ID and AccessKey secret.
        // Note that the AccessKey ID obtained from STS starts with "STS".
        String stsAccessKeyId = "STS.****************";
        String stsAccessKeySecret = "yourAccessKeySecret";
        String stsSecurityToken = "yourSecurityToken";
        
        // Create a static credential provider and explicitly set the temporary AccessKey pair and security token.
        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
                stsAccessKeyId,
                stsAccessKeySecret,
                stsSecurityToken
        );
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Use RAM role ARN credentials

If your application requires authorized access to OSS, such as for cross-account access, you can use the Alibaba Cloud Resource Name (ARN) of a RAM role to initialize a credential provider. This method uses an STS token. When you specify the RAM role ARN, the credential tool automatically obtains and refreshes the STS token by calling the AssumeRole API operation. You can also set the policy parameter to further restrict the role's permissions.

Important
  • An Alibaba Cloud account has full permissions over its resources. If the AccessKey pair of an Alibaba Cloud account is leaked, it poses a significant security risk to your system. We recommend using the AccessKey pair of a RAM user with the minimum required permissions.

  • To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret are displayed only when the pair is created. You must save them immediately. If you forget the AccessKey pair, create a new one to replace it.

  • To obtain the ARN of a RAM role, see Create a RAM role.

Add a dependency

Add the Alibaba Cloud credentials management dependency to your pom.xml file:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Configure an AccessKey pair and a RAM role ARN

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java.
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure RAM role ARN credentials.
        Config credentialConfig = new Config()
                .setType("ram_role_arn")
                // Obtain the RAM user's AccessKey pair (AccessKey ID and AccessKey secret) from environment variables.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole
                // You can set the RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn("acs:ram::123456789012****:role/adminrole")
                // The role session name. You can set the RoleSessionName by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("your-session-name")
                // Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                .setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
                // Optional. The validity period of the role session in seconds. The default is 3,600 seconds (1 hour).
                .setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider to dynamically load credentials.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Use ECS RAM role credentials

If your application runs on an ECS instance, an ECI instance, or a Container Service for Kubernetes worker node, we recommend using an ECS RAM role to initialize the credential provider. This method uses an STS token. When you attach an ECS RAM role to an instance, the SDK automatically retrieves and refreshes the role's temporary STS token. This method eliminates the risk of manually managing an AccessKey pair or STS token. For more information about how to create an ECS RAM role, see Create a RAM role.

Add a dependency

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Configure an ECS RAM role

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java.
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure ECS RAM role credentials.
        Config credentialConfig = new Config()
                .setType("ecs_ram_role")      // The access credential type. Must be ecs_ram_role.
                .setRoleName("EcsRoleExample"); // Optional. The name of the RAM role that is attached to the ECS instance. If you do not set this parameter, the role is automatically retrieved. We strongly recommend that you set this parameter to reduce requests.

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider to dynamically load credentials.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Use OIDC role ARN credentials

After configuring a RAM role for worker nodes in Container Service for Kubernetes, applications in Pods on those nodes can obtain an STS token for the attached role through the metadata service, similar to applications on ECS. However, you might not want untrusted applications, such as those submitted by your customers, to obtain the STS token for the worker node's instance RAM role. To allow these applications to obtain the required STS tokens with minimal permissions while protecting your cloud resources, you can use RAM Roles for Service Accounts (RRSA). This method uses an STS token. Alibaba Cloud container clusters create and mount the corresponding service account OpenID Connect (OIDC) token file for different application Pods and inject the configuration information into environment variables. The credential tool uses this configuration to call the AssumeRoleWithOIDC STS operation, exchanging the OIDC token for a role-bound STS token. This method eliminates the risks of manually managing an AccessKey pair or STS token. For more information, see Use RRSA to configure RAM permissions for a ServiceAccount and isolate Pod permissions.

Add a dependency

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Configure an OIDC role ARN

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java.
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure OIDC role ARN credentials.
        Config credentialConfig = new Config()
                // Specify the credential type. Must be oidc_role_arn.
                .setType("oidc_role_arn")
                // The ARN of the RAM role. You can set the RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"))
                // The ARN of the OIDC provider. You can set the OidcProviderArn by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                .setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"))
                // The file path of the OIDC token. You can set the OidcTokenFilePath by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                .setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"))
                // The role session name. You can set the RoleSessionName by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("your-session-name")
                // Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                .setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
                // Optional. The validity period of the role session in seconds. The default is 3,600 seconds (1 hour).
                .setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider to dynamically load credentials.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Custom credential provider

If the preceding methods do not meet your needs, you can implement a custom credential provider. The SDK for Java supports multiple ways to do this.

Supplier interface

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;

public class OSSExample {
    public static void main(String[] args) {
        // Create a custom credential provider.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            // TODO: Implement your custom credential retrieval logic.
            
            // Return long-term credentials.
            return new Credentials("access_key_id", "access_key_secret");
            
            // Return an STS token (if needed).
            // return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
        });
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

CredentialsProvider interface

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;

public class CustomCredentialsProvider implements CredentialsProvider {
    
    @Override
    public Credentials getCredentials() {
        // TODO: Implement your custom credential retrieval logic.
        
        // Return long-term credentials.
        return new Credentials("access_key_id", "access_key_secret");
        
        // Return an STS token (if needed).
        // For temporary credentials, you must refresh them based on their expiration time.
        // return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
    }
}

public class OSSExample {
    public static void main(String[] args) {
        // Create a custom credential provider.
        CredentialsProvider credentialsProvider = new CustomCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Anonymous access

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

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as or ap-southeast-1.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.AnonymousCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Create an anonymous credential provider.
        CredentialsProvider credentialsProvider = new AnonymousCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("<region-id>") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations.
            // Note: Anonymous access applies only to public-read resources.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Code examples

Feature category

Description

Sync version

Async version

Bucket

Create a bucket

PutBucket.java

PutBucketAsync.java

List buckets

ListBuckets.java

ListBucketsAsync.java

Get bucket information

GetBucketInfo.java

GetBucketInfoAsync.java

Get bucket region

GetBucketLocation.java

GetBucketLocationAsync.java

Get bucket storage statistics

GetBucketStat.java

GetBucketStatAsync.java

Delete a bucket

DeleteBucket.java

DeleteBucketAsync.java

Object upload

Simple upload

PutObject.java

PutObjectAsync.java

Append upload

AppendObject.java

AppendObjectAsync.java

Multipart upload

MultipartUpload.java

MultipartUploadAsync.java

List multipart upload tasks

ListMultipartUploads.java

ListMultipartUploadsAsync.java

List uploaded parts

ListParts.java

ListPartsAsync.java

Cancel a multipart upload

AbortMultipartUpload.java

AbortMultipartUploadAsync.java

Object download

Simple download

GetObject.java

GetObjectAsync.java

Object management

Copy an object

CopyObject.java

CopyObjectAsync.java

Check if an object exists

HeadObject.java

HeadObjectAsync.java

List objects

ListObjects.java

ListObjectsAsync.java

List objects (V2)

ListObjectsV2.java

ListObjectsV2Async.java

Delete an object

DeleteObject.java

DeleteObjectAsync.java

Delete multiple objects

DeleteMultipleObjects.java

DeleteMultipleObjectsAsync.java

Get object metadata

GetObjectMeta.java

GetObjectMetaAsync.java

Archived object

Restore an object

RestoreObject.java

RestoreObjectAsync.java

Clean up a restored object

CleanRestoredObject.java

CleanRestoredObjectAsync.java

Symbolic link

Create a symbolic link

PutSymlink.java

PutSymlinkAsync.java

Get a symbolic link

GetSymlink.java

GetSymlinkAsync.java

Object tagging

Set object tags

PutObjectTagging.java

PutObjectTaggingAsync.java

Get object tags

GetObjectTagging.java

GetObjectTaggingAsync.java

Delete object tags

DeleteObjectTagging.java

DeleteObjectTaggingAsync.java

Access control

Set bucket ACL

PutBucketAcl.java

PutBucketAclAsync.java

Get bucket ACL

GetBucketAcl.java

GetBucketAclAsync.java

Set object ACL

PutObjectAcl.java

PutObjectAclAsync.java

Get object ACL

GetObjectAcl.java

GetObjectAclAsync.java

Versioning

Set bucket versioning

PutBucketVersioning.java

PutBucketVersioningAsync.java

Get versioning status

GetBucketVersioning.java

GetBucketVersioningAsync.java

List object versions

ListObjectVersions.java

ListObjectVersionsAsync.java

Cross-Origin Resource Sharing (CORS)

Set CORS rules

PutBucketCors.java

PutBucketCorsAsync.java

Get CORS rules

GetBucketCors.java

GetBucketCorsAsync.java

Delete CORS rules

DeleteBucketCors.java

DeleteBucketCorsAsync.java

Preflight request

OptionObject.java

OptionObjectAsync.java

System features

Query endpoint information

DescribeRegions.java

DescribeRegionsAsync.java