OSS Java SDK V2
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.
Quick start
The following flowchart shows how to integrate OSS Java SDK V2.
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=trueConfigure 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
Run the following commands to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrcRun the following command to apply the changes.
source ~/.bashrcRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in Terminal to check the default shell type.
echo $SHELLFollow the steps for your default shell type.
Zsh
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrcRun the following command to apply the changes.
source ~/.zshrcRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profileRun the following command to apply the changes.
source ~/.bash_profileRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
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"Run the following commands to verify that the environment variables are set.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
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)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.
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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?
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.
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
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'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 examplecn-hangzhouor .
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.
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 examplecn-hangzhouor .
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.
To quickly obtain temporary STS credentials through OpenAPI, see AssumeRole - Obtain temporary identity credentials for a RAM role.
To obtain temporary STS credentials with an SDK, see Access OSS by using STS temporary credentials.
When you generate an STS token, you must specify its expiration time. After the token expires, it becomes invalid and can't be used.
For a list of STS service endpoints, see Endpoints.
Configure environment variables
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 examplecn-hangzhouor .
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.
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 examplecn-hangzhouor .
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.
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 examplecn-hangzhouor .
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 | ||
List buckets | |||
Get bucket information | |||
Get bucket region | |||
Get bucket storage statistics | |||
Delete bucket | |||
File upload | Simple upload | ||
Append upload | |||
Multipart upload | |||
List multipart upload tasks | |||
List uploaded parts | |||
Cancel a multipart upload | |||
File download | Simple download | ||
File management | Copy a file | ||
Check if a file exists | |||
List files | |||
List files V2 | |||
Delete a file | |||
Delete multiple files | |||
Get file metadata | |||
Archived object | Restore a file | ||
Clean up a restored file | |||
Symbolic link | Create a symbolic link | ||
Get a symbolic link | |||
Object tagging | Set object tags | ||
Get object tags | |||
Delete object tags | |||
Access control | Set bucket ACL | ||
Get bucket ACL | |||
Set object ACL | |||
Get object ACL | |||
Versioning | Set versioning | ||
Get versioning status | |||
List object versions | |||
Cross-domain access | Set CORS rules | ||
Get CORS rules | |||
Delete CORS rules | |||
Preflight request | |||
System features | Query endpoint information |