OSS Java SDK V2

Updated at:

Use OSS Java SDK V2 to connect Java applications to Alibaba Cloud Object Storage Service (OSS) and upload, download, and manage cloud objects. It suits websites, enterprises, and developers that need cloud file storage.

Github | OSS SDK for Java API | mvnrepository | deepwiki

Quick start

The following flowchart shows how to integrate OSS Java SDK V2.

image

Prerequisites

Java 8 or later.

Run java -version to check your Java version. If Java isn't installed or your version is earlier than Java 8, download and install Java.

Install the SDK

Install OSS Java SDK V2 with Maven, or build it from source.

Maven

Add the following dependency to pom.xml and replace <version> with the latest version listed in the Maven Repository:

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

Source code

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

mvn clean install -DskipTests -Dgpg.skip=true

Configure access credentials

Set a RAM user's AccessKey pair as environment variables to use as credentials.

In the RAM console, create a RAM user with Access with a permanent AccessKey, save the AccessKey pair, and grant the AliyunOSSFullAccess policy 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 set.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Run the following command in Terminal to check the default shell type.

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

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

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

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

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

Initialize a client

  • OSSClient implements AutoCloseable. When you create an instance and use it with try-with-resources, resources are released automatically, so you don't need to call close manually.

  • Creating and destroying an OSSClient instance is time-consuming. You can reuse a single instance with the singleton pattern, but you must call close manually before the application terminates. Otherwise, resources leak.

    Singleton pattern

    Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
    import com.aliyun.sdk.service.oss2.OSSClient;
    import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
    
    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;
        }
    
        // Close the OSSClient (must be called explicitly).
        public static void shutdown() {
            try {
                getInstance().close();
            } catch (Exception e) {
                // Handle the close exception.
            }
        }
    }

Synchronous OSSClient

Use a synchronous OSSClient if you need each operation to finish before you continue.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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

Use an asynchronous OSSClient if you need to process multiple OSS operations concurrently and don't depend on the result of each operation.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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);
        }
    }
}

The output lists the buckets that the current account owns in all regions.

Client configuration

What client settings are supported?

Parameter

Description

region

(Required) Region to which requests are sent

credentialsProvider

(Required) Credentials used to access OSS

endpoint

Endpoint used to access OSS

httpClient

HTTP client

retryMaxAttempts

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

retryer

Retry implementation for HTTP requests

connectTimeout

Timeout for establishing a connection. Default: 5 seconds

readWriteTimeout

Timeout for reading and writing data. Default: 20 seconds

insecureSkipVerify

Whether to skip SSL certificate verification. Default: SSL certificates are verified

enabledRedirect

Whether to enable HTTP redirects. Default: disabled

proxyHost

Proxy server

signatureVersion

Signature version. Default: v4

disableSsl

Whether to use HTTP instead of HTTPS. Default: HTTPS

usePathStyle

Whether to use path-style requests. Default: requests use the bucket-hosted domain

useCName

Whether to access OSS through a custom domain. Default: disabled

useDualStackEndpoint

Whether to use dual-stack endpoints. Default: disabled

useAccelerateEndpoint

Whether to use transfer acceleration endpoints. Default: disabled

useInternalEndpoint

Whether to use internal endpoints. Default: disabled

additionalHeaders

Additional request headers to sign. Valid for V4 signatures

userAgent

Additional User-Agent information

Use a custom domain

When you access OSS through the default domain, files may be blocked or can't be previewed. With Access OSS through a custom domain name, you can preview files directly in a browser and accelerate distribution with CDN.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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>";

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

        // Create an OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                // Set this to true to enable CNAME. Otherwise, the custom domain can't be used.
                .useCName(true)
                .build()) {

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

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

Timeout settings

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Set the connection timeout. Default: 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Set the read/write timeout. Default: 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 you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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) {
        /*
         * Retry policy configuration:
         *
         * Default retry policy:
         * If you don't configure a retry policy, the SDK uses StandardRetryer as the client's default implementation. Its default settings are:
         * - maxAttempts: Maximum number of attempts. Default: 3
         * - maxBackoff: Maximum backoff time in seconds. Default: 20
         * - baseDelay: Base delay in seconds. Default: 0.2
         * - backoffDelayer: Backoff algorithm. Default: FullJitter
         *   Formula: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff)
         * - errorRetryables: Retryable error types, including HTTP status codes, service error codes, and client errors
         *
         * When a retryable error occurs, the request is delayed and then retried based on the configuration.
         * The total request delay increases with the number of retries. If the default settings don't meet your needs,
         * configure the retry parameters or modify the retry implementation.
         */

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

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

        // Retry policy configuration examples:

        // 1. Customize the maximum number of attempts. Default: 3. This example sets it to 5.
        Retryer customRetryer = StandardRetryer.newBuilder()
                .maxAttempts(5)
                .build();

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

        // 3. Customize the backoff algorithm.
        // Replace the default FullJitter algorithm with a fixed-delay algorithm that waits 2 seconds each time.
        // Retryer customRetryer = StandardRetryer.newBuilder()
        //         .backoffDelayer(new FixedDelayBackoff(Duration.ofSeconds(2)))
        //         .build();

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

        // Create an OSSClient with the configured settings.
        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 protocol

Call disableSsl(true) to send requests over HTTP instead of HTTPS.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Send requests over HTTP.
                .disableSsl(true)
                .build()) {

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

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

Default request headers

Use defaultRequestHeaders to set default HTTP headers for every request that the client sends, such as a business tracking ID. Headers set at the client level are added to each request automatically, so you don't need to pass them in every call.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

import java.util.HashMap;
import java.util.Map;

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. This example uses China (Hangzhou): cn-hangzhou.
        String region = "cn-hangzhou";

        // Configure client-level default request headers.
        Map<String, String> defaultHeaders = new HashMap<>();
        defaultHeaders.put("x-oss-request-tag", "my-business-tag");

        // Create an OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Set the default request headers.
                .defaultRequestHeaders(defaultHeaders)
                .build()) {

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

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

Use an internal endpoint

Use an internal endpoint to access OSS resources in the same region. This reduces traffic costs and improves access speed.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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();

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

        // // Option 2: Directly specify the region and endpoint.
        // // Specify the region where the bucket is located.
        // String region = "<region-id>";
        // // Specify the internal endpoint of the region where the bucket is located.
        // String endpoint = "<endpoint>";

        // Create an OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useInternalEndpoint(true)
                // .endpoint(endpoint) // If you use Option 2, uncomment this line and comment out the line above.
                .build()) {

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

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

Use a transfer acceleration endpoint

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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();

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

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

        // Create an OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useAccelerateEndpoint(true)
                // .endpoint(endpoint) // If you use Option 2, uncomment this line and comment out the line above.
                .build()) {

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

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

Use a dedicated domain

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 dedicated domain. Example: https://service.corp.example.com
        String endpoint = "https://service.corp.example.com";

        // Create an OSSClient with the configured settings.
        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());
        }
    }
}

Use a Finance Cloud endpoint

The following sample code shows how to configure OSSClient with a Finance Cloud endpoint.

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 and endpoint.
        // Specify the region where the bucket is located. This example uses China (Hangzhou) Finance Cloud, so set Region to cn-hangzhou-finance.
        String region = "cn-hangzhou-finance";
        // Specify the internal endpoint of the region where the bucket is located. This example uses China (Hangzhou) Finance Cloud, so set Endpoint to 'https://oss-cn-hzjbp-a-internal.aliyuncs.com'.
        // To use the HTTP protocol, specify 'http://oss-cn-hzjbp-a-internal.aliyuncs.com' as the domain.
        String endpoint = "https://oss-cn-hzjbp-a-internal.aliyuncs.com";

        // Create an OSSClient with the configured settings.
        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());
        }
    }
}

Use a Gov Cloud endpoint

The following sample code shows how to configure OSSClient with a Gov Cloud endpoint.

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 and endpoint.
        // Specify the region where the bucket is located. This example uses China North 2 (Beijing) Alibaba Gov Cloud 1, so set Region to cn-north-2-gov-1.
        String region = "cn-north-2-gov-1";
        // Specify the internal endpoint of the region where the bucket is located. This example uses China North 2 (Beijing) Alibaba Gov Cloud 1, so set Endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
        // To use the HTTP protocol, specify 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com' as the domain.
        String endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com";

        // Create an OSSClient with the configured settings.
        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());
        }
    }
}

Use a custom HTTP client

If the standard configuration options don't meet your needs, use a custom HTTP client.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
Note

The following example shows a custom HTTP client 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>";

        // Configure the HTTP client options.
        HttpClientOptions httpClientOptions = HttpClientOptions.custom()
                // Connection timeout. Default: 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Read/write timeout for application data. Default: 20 seconds.
                .readWriteTimeout(Duration.ofSeconds(30))
                // Maximum number of connections. Default: 1024.
                .maxConnections(2048)
                // Whether to skip certificate verification. Default: do not skip.
                .insecureSkipVerify(false)
                // Whether to enable HTTP redirects. Default: disabled.
                .redirectsEnabled(false)
                // Set the proxy server.
                // .proxyHost("http://user:passswd@proxy.example-***.com")
                .build();

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

        // Create an OSSClient with the configured settings.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .httpClient(httpClient)
                .build()) {

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

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

Access credential configuration

OSS Java SDK V2 supports several ways to configure access credentials. Choose the initialization method that fits your authentication and authorization requirements.

How do I choose an access credential?

Credentials provider initialization method

Scenario

Java SDK V2 support

Underlying credential

Credential validity

Credential rotation or refresh

Use a RAM user's AccessKey pair

Applications deployed in secure, stable environments that are not easily exposed to external attacks and that need long-term access to cloud services without frequent credential rotation

Built-in support

AK

Long-term

Manual rotation

Use temporary STS credentials

Applications deployed in untrusted environments, where you want to control the validity period and permissions of access

Built-in support

STS Token

Temporary

Manual refresh

Use RAM role ARN credentials

Cross-account access to OSS resources, where you obtain temporary credentials by assuming a RAM role

Extended support

STS Token

Temporary

Automatic refresh

Use ECS RAM role credentials

Applications running on ECS instances, ECI instances, or Container Service for Kubernetes

Extended support

STS Token

Temporary

Automatic refresh

Use OIDC Role ARN credentials

Pod-level permission isolation through the RRSA feature of Container Service for Kubernetes

Extended support

STS Token

Temporary

Automatic refresh

Use custom access credentials

When none of the preceding methods meet your requirements, you can customize how credentials are obtained

Built-in support

Custom

Custom

Custom

Anonymous access

Access OSS resources with public read permissions without providing any credentials

Built-in support

None

None

None

Credential features marked Extended support require the custom access credential method together with the Alibaba Cloud credentials library. The SDK provides built-in support for basic credential configuration. You can enable extended features by integrating the credentials-java library.

Use a RAM user's AccessKey pair

If your application runs in a secure, stable environment that is not easily exposed to external attacks, needs long-term access to OSS, and can't rotate credentials frequently, initialize the credentials provider with the AccessKey pair (Access Key ID and Access Key Secret) of your Alibaba Cloud account or a RAM user. This method requires you to manually maintain an AccessKey pair, which increases security risks and maintenance complexity.

Important
  • An Alibaba Cloud account has full permissions on resources. If its AccessKey pair is leaked, the risk to your system is significant. Don't use an Alibaba Cloud account's AccessKey pair. Use the AccessKey pair of a RAM user with minimal permissions instead.

  • To create an AccessKey pair for a RAM user, go to Create an AccessKey pair. The Access Key ID and Access Key Secret of a RAM user are displayed only when the pair is created. Save them promptly. If you lose them, create a new AccessKey pair and rotate it.

Configure environment variables

Linux/macOS

  1. Configure environment variables with 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 take effect:

    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)

Sample code

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 credentials 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 client to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Static credential configuration

The following sample code hard-codes the access credential by explicitly specifying the AccessKey pair to use.

Warning

Don't embed access credentials in production applications. Use this method for testing only.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 credentials provider and explicitly set the AccessKey pair.
        // Replace the key pair with the Access Key ID and Access Key Secret of your RAM user.
        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 client to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Use temporary STS credentials

If your application needs temporary access to OSS, initialize the credentials provider with temporary identity credentials from Security Token Service (STS): an Access Key ID, an Access Key Secret, and a security token. This method requires you to manually maintain the STS token, which increases security risks and maintenance complexity. If you need temporary access to OSS multiple times, you must refresh the STS token manually.

Configure environment variables

Important
  • The credentials used here are the temporary identity credentials obtained from STS (an Access Key ID, an Access Key Secret, and a security token), not the AccessKey pair of a RAM user.

  • An Access Key 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>

Sample code

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 credentials required to access OSS 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 client to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Static credential configuration

The following sample code hard-codes the access credential by explicitly specifying the temporary AccessKey pair to use.

Warning

Don't embed access credentials in production applications. Use this method for testing only.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 temporary Access Key ID and Access Key Secret that you obtained.
        // The Access Key ID obtained from STS starts with "STS".
        String stsAccessKeyId = "STS.****************";
        String stsAccessKeySecret = "yourAccessKeySecret";
        String stsSecurityToken = "yourSecurityToken";
        
        // Create a static credentials provider and explicitly set the temporary AccessKey pair and STS 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 client to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Use RAM role ARN credentials

If your application needs authorized access to OSS, for example cross-account access, initialize the credentials provider with RAMRoleARN. This method is backed by STS tokens. After you specify the ARN (Alibaba Cloud Resource Name) of a RAM role, the credentials library requests an STS token from STS and, before the session expires, calls AssumeRole to obtain a new token. You can also assign a value to the policy parameter to restrict the RAM role to a smaller permission set.

Important
  • An Alibaba Cloud account has full permissions on resources. If its AccessKey pair is leaked, the risk to your system is significant. Don't use an Alibaba Cloud account's AccessKey pair. Use the AccessKey pair of a RAM user with minimal permissions instead.

  • To create an AccessKey pair for a RAM user, go to Create an AccessKey. The Access Key ID and Access Key Secret of a RAM user are displayed only when the pair is created. Save them promptly. If you lose them, create a new AccessKey pair and rotate it.

  • To obtain a RAM role ARN, see CreateRole.

Add a dependency

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

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

Configure an AccessKey pair and a RAM role ARN as access credentials

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 RAMRoleARN credentials.
        Config credentialConfig = new Config()
                .setType("ram_role_arn")
                // Obtain the RAM user's Access Key ID and Access Key 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 RoleArn through the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn("acs:ram::123456789012****:role/adminrole")
                // The role session name. You can set RoleSessionName through the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("your-session-name")
                // A smaller permission policy. Optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                .setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
                // The validity period of the role session in seconds. Default: 3600 seconds (1 hour). Optional.
                .setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credentials provider for dynamic credential loading.
        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 to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Use ECS RAM role credentials

If your application runs on an ECS instance, an ECI instance, or a worker node in Container Service for Kubernetes, initialize the credentials provider with ECSRAMRole. This method is backed by STS tokens. ECSRAMRole associates a role with an ECS instance, an ECI instance, or a worker node in Container Service for Kubernetes, and refreshes STS tokens automatically inside the instance. You don't need to provide an AccessKey pair or an STS token, which eliminates the risk of manually maintaining them. To obtain an ECSRAMRole, see CreateRole.

Add a dependency

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

Configure ECSRAMRole as access credentials

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 ECSRAMRole credentials.
        Config credentialConfig = new Config()
                .setType("ecs_ram_role")      // The credential type. Fixed to ecs_ram_role.
                .setRoleName("EcsRoleExample"); // The name of the RAM role granted to the ECS instance. Optional. If you don't set it, the role is retrieved automatically. Set it to reduce requests.

        Client credentialClient = new Client(credentialConfig);

        // Create a credentials provider for dynamic credential loading.
        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 to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Use OIDC Role ARN credentials

After you assign a RAM role to a worker node in Container Service for Kubernetes, applications in pods on that node can obtain STS tokens for the associated role from the metadata server (Meta Data Server), just as applications deployed on ECS instances do. However, if the cluster hosts untrusted applications—for example, applications submitted by your customers whose code you can't inspect—you may not want them to obtain STS tokens for the RAM role associated with the worker node's instance through the metadata server. To protect your cloud resources and still let these untrusted applications securely obtain the STS tokens they need, use the RAM Roles for Service Account (RRSA) feature. RRSA is backed by STS tokens and lets you apply least privilege at the application level. Alibaba Cloud creates and mounts a service account OIDC token file for each application pod and injects the related configuration into environment variables. The credentials tool reads this configuration, calls the AssumeRoleWithOIDC operation of STS, and exchanges the OIDC token for an STS token bound to the role. You don't need to provide an AccessKey pair or an STS token, which eliminates the risk of manually maintaining them. For details, see Use RRSA for pod-level access control.

Add a dependency

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

Configure OIDCRoleARN as access credentials

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 OIDCRoleARN credentials.
        Config credentialConfig = new Config();
        // Specify the credential type. Fixed to oidc_role_arn.
        credentialConfig.setType("oidc_role_arn");
        credentialConfig.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"));
        credentialConfig.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"));
        credentialConfig.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"));
        credentialConfig.setRoleSessionName("your-session-name");
        credentialConfig.setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}");
        credentialConfig.setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credentials provider for dynamic credential loading.
        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 to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Use custom access credentials

If the preceding credential configuration methods don't meet your requirements, customize how the SDK obtains credentials. The Java SDK supports several implementation options.

Implement with the Supplier interface

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 credentials 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 temporary STS credentials 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 client you created to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Implement the CredentialsProvider interface

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;

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 temporary STS credentials if needed.
        // For temporary credentials, refresh them before they expire.
        // 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 credentials 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 client you created to perform subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Anonymous access

If you only need to access OSS resources that have public read permissions, use anonymous access. This method doesn't require any credentials.

Before you run the sample code, replace <region-id> with the actual Regions and endpoints, for example cn-hangzhou or .
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 credentials 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 client you created to perform subsequent operations...
            // Note: Anonymous access can only access resources with public read permissions.
            
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Sample code

Feature classification

Example description

Synchronous version

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

DeleteBucket.java

DeleteBucketAsync.java

File 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

File download

Simple download

GetObject.java

GetObjectAsync.java

File management

Copy a file

CopyObject.java

CopyObjectAsync.java

Check if a file exists

HeadObject.java

HeadObjectAsync.java

List files

ListObjects.java

ListObjectsAsync.java

List files V2

ListObjectsV2.java

ListObjectsV2Async.java

Delete a file

DeleteObject.java

DeleteObjectAsync.java

Delete multiple files

DeleteMultipleObjects.java

DeleteMultipleObjectsAsync.java

Get file metadata

GetObjectMeta.java

GetObjectMetaAsync.java

Archived object

Restore a file

RestoreObject.java

RestoreObjectAsync.java

Clean up a restored file

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 versioning

PutBucketVersioning.java

PutBucketVersioningAsync.java

Get versioning status

GetBucketVersioning.java

GetBucketVersioningAsync.java

List object versions

ListObjectVersions.java

ListObjectVersionsAsync.java

Cross-domain access

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