All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK

Last Updated:Mar 23, 2026

Object Storage Service (OSS) SDKs let you integrate OSS directly into your application. This guide uses OSS SDK for Java to walk through a complete workflow: create a bucket, upload an object, download it, list objects, then delete everything.

Prerequisites

Before you begin, make sure you have:

Configure environment variables

Credentials are passed to the SDK through environment variables to avoid hardcoding sensitive information in your code.

Step 1: Create an AccessKey pair

Create an AccessKey pair for a Resource Access Management (RAM) user with full OSS access permissions.

Create an AccessKey pair using ROS

To create an AccessKey pair quickly, go to the wizard for template-based stack creation, select I confirm that Alibaba Cloud ROS may create RAM resources in the Security Confirmation section, and click Create.

1.png

After the stack is created, copy the AccessKey pair from the Outputs tab.

image

Step 2: Set environment variables

Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET for your operating system.

Linux

  1. Add the 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 variables are set:

       echo $OSS_ACCESS_KEY_ID
       echo $OSS_ACCESS_KEY_SECRET

macOS

First, check your default shell:

echo $SHELL

Then set the variables based on the result.

Zsh
  1. Add the 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 variables are set:

       echo $OSS_ACCESS_KEY_ID
       echo $OSS_ACCESS_KEY_SECRET
Bash
  1. Add the 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 variables are set:

       echo $OSS_ACCESS_KEY_ID
       echo $OSS_ACCESS_KEY_SECRET

Windows

CMD
  1. Set the variables:

       setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
       setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Verify the variables are set:

       echo %OSS_ACCESS_KEY_ID%
       echo %OSS_ACCESS_KEY_SECRET%
PowerShell
  1. Set the variables:

       [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 variables are set:

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

After setting environment variables, restart your IDE, command-line interface (CLI), and any background services to load the updated values.

Install OSS SDK for Java

Step 1: Check your Java version

Run the following command to check your Java version:

java -version

OSS SDK for Java requires Java 7 or later. If Java is not installed or your version is earlier than 7, download a compatible version.

Step 2: Add the SDK dependency

Use OSS SDK for Java V3.17.4.

Maven (recommended)

Add the following dependency to your pom.xml:

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.17.4</version>
</dependency>

If you use Java 9 or later, also add these jaxb-related dependencies:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>

Eclipse (JAR import)

  1. Download OSS SDK for Java.zip.

  2. Decompress the package.

  3. Copy aliyun-sdk-oss-3.17.4.jar and all files in the lib directory to your project.

  4. In Eclipse, right-click your project and choose Properties > Java Build Path > Add JARs.

  5. Select all JAR files you copied and import them to Libraries.

IntelliJ IDEA (JAR import)

  1. Download OSS SDK for Java.zip.

  2. Decompress the package.

  3. Copy aliyun-sdk-oss-3.17.4.jar and all JAR files in the lib directory to your project.

  4. In IntelliJ IDEA, choose File > Project Structure > Modules > Dependencies > + > JARs or directories.

  5. Select all JAR files you copied and import them to External Libraries.

Run the complete example

The following example covers the full workflow in a single runnable program. It uses the Singapore region (ap-southeast-1) so you can run it immediately without any endpoint changes.

Important

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

The program performs six operations in sequence: creates a bucket, uploads a string as an object, downloads and reads the object, lists the bucket contents, deletes the object, then deletes the bucket.

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.

import java.io.*;
import java.util.Random;

import com.aliyun.oss.*;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;

public class OssJavaSdkQuickStart {
    /** Generates a unique bucket name. */
    public static String generateUniqueBucketName(String prefix) {
        // Get the current timestamp.
        String timestamp = String.valueOf(System.currentTimeMillis());
        // Generate a random number between 0 and 9999.
        Random random = new Random();
        int randomNum = random.nextInt(10000); // Generate a random number between 0 and 9999.
        // Concatenate the parts to form a unique bucket name.
        return prefix + "-" + timestamp + "-" + randomNum;
    }

    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // This example uses the Singapore region to illustrate process. Set the endpoint to https://oss-ap-southeast-1.aliyuncs.com. Replace it with the actual endpoint.
        String endpoint = "https://oss-ap-southeast-1.aliyuncs.com";
        String bucketName = generateUniqueBucketName("demo");
        // Specify the region where the bucket is located. This example uses Singapore. Set the region to ap-southeast-1.
        String region = "ap-southeast-1";

        // Obtain access credentials from environment variables. Before you run the sample code, configure the environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 1. Create a bucket.
            ossClient.createBucket(bucketName);
            System.out.println("1. Bucket " + bucketName + " created.");
            // 2. Upload a file.
            String objectName = "exampledir/exampleobject.txt";
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            System.out.println("2. File " + objectName + " uploaded.");
            // 3. Download the file.
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. Content of the downloaded file:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. List files.
            System.out.println("4. Files in the bucket:");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (size = " + objectSummary.getSize() + ")");
            }
            // 5. Delete the file.
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. File " + objectName + " deleted.");
            // 6. Delete the bucket.
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " deleted.");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

A successful run produces output similar to the following:

1. Bucket demo-1731651903982-4074 created.
2. File exampledir/exampleobject.txt uploaded.
3. Content of the downloaded file:
Hello OSS
4. Files in the bucket:
 - exampledir/exampleobject.txt (size = 9)
5. File exampledir/exampleobject.txt deleted.
6. Bucket demo-1731651903982-4074 deleted.

SDKs for other languages

SDKs for other languages support the same bucket management and object operations.

What's next

Now that you have a working SDK setup, explore common follow-up tasks: