OSSClient is the Java client of Object Storage Service (OSS). It is used to manage OSS resources, such as buckets and objects. To use OSS SDK for Java to initiate a request, you must initialize an OSSClient instance and modify the default configuration items of the ClientConfiguration configuration class based on your business requirements.
Usage notes
Before you initialize an OSSClient instance, you must configure access credentials. In this topic, access credentials are obtained from environment variables. For more information, see Configure access credentials.
Create an OSSClient instance
OSSClient is thread-safe and allows you to use multiple threads to access the same instance. You can reuse the same OSSClient instance or create multiple OSSClient instances based on your business requirements.
An OSSClient instance has a connection pool. If you no longer use an OSSClient instance, call the shutdown method to shut down the OSSClient instance. This prevents resource exhaustion caused by an excessive number of OSSClient instances.
(Recommended) Use the V4 signature algorithm
We recommend that you use the V4 signature algorithm which provides better security.
When you initialize an OSSClient instance by using the V4 signature algorithm, you must specify an endpoint. Example: https://oss-cn-hangzhou.aliyuncs.com.
You must specify an Alibaba Cloud Region ID as the identifier of the region in which the request is initiated. Example: cn-hangzhou.
You must explicitly declare the use of the V4 signature algorithm in your code. Example: SignVersion.V4.
OSS SDK for Java 3.17.4 and later support the V4 signature algorithm.
Create an OSSClient instance by using an OSS endpoint
The following sample code provides an example on how to create an OSSClient instance and use the V4 signature algorithm by using an OSS endpoint.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Create an OSSClient instance in Apsara Stack or a private region
The following sample code provides an example on how to create an OSSClient instance in Apsara Stack or a private region:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Disable CNAME.
clientBuilderConfiguration.setSupportCname(false);
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Create an OSSClient instance by using a custom domain name
The following sample code provides an example on how to create an OSSClient instance by using a custom domain name. For more information, see Map a custom domain name to the default domain name of a bucket.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify a custom domain name.
String endpoint = "yourEndpoint";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Enable CNAME.
clientBuilderConfiguration.setSupportCname(true);
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Create an OSSClient instance by using an IP address
The following sample code provides an example on how to create an OSSClient instance by using an IP address:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify an IP address as an endpoint in specific scenarios, such as scenarios that involve a private region. In specific scenarios, you must specify the IP address based on your business requirements.
String endpoint = "https://10.10.10.10";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Enable access from a second-level domain. By default, access from second-level domains is disabled. OSS SDK for Java 2.1.2 or later automatically detects IP addresses. If you use OSS SDK for Java whose version is earlier than 2.1.2, you must specify this parameter.
clientBuilderConfiguration.setSLDEnabled(true);
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
(Not recommended) Use the V1 signature algorithm
From March 1, 2025, the V1 signature algorithm of OSS is no longer available to new customers with new UIDs. From September 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.
Create an OSSClient instance by using an OSS endpoint
The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint. For more information about the OSS endpoints of different regions, see Regions and endpoints.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance by using a custom domain name
The following sample code provides an example on how to create an OSSClient instance by using a custom domain name. For more information, see Map a custom domain name to the default domain name of a bucket.
If you use a custom domain name, the ossClient.listBuckets method is unavailable.
// Specify a custom domain name.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create ClientBuilderConfiguration and change the default values of the parameters based on your business requirements.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Specify whether to use CNAME. CNAME is used to map the custom domain name to the bucket.
conf.setSupportCname(true);
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf);
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance by using access credentials obtained from STS
The following sample code provides an example on how to create an OSSClient instance by using access credentials obtained from Security Token Service (STS):
For more information about how to configure STS, see Use temporary access credentials provided by STS to access OSS.
You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials. For more information, see STS SDK overview.
The temporary access credentials consist of a temporary AccessKey pair and a security token. The temporary AccessKey pair consists of an AccessKey ID and an AccessKey secret. The validity period of temporary access credentials is in seconds. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
For the complete sample code that is used to create an OSSClient instance by using access credentials obtained from STS, see Use a signed URL to download an object.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Obtain temporary access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance by using STSAssumeRole
The following sample code provides an example on how to create an OSSClient instance by using STSAssumeRole:
// Specify the region for which you want to authorize STSAssumeRole to access. In this example, the China (Hangzhou) region is used. Specify your actual region.
String region = "cn-hangzhou";
// Obtain the AccessKey pair of the RAM user from the environment variables. Before you run the sample code, make sure that the environment variables are configured.
String accessKeyId = System.getenv("ALIYUN_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIYUN_ACCESS_KEY_SECRET");
// Obtain the Alibaba Cloud Resource Name (ARN) of the RAM role from the environment variable. Before you run the sample code, make sure that the environment variables are configured.
String roleArn = System.getenv("ALIYUN_STS_ROLE_ARN");
// Create an STSAssumeRoleSessionCredentialsProvider instance.
STSAssumeRoleSessionCredentialsProvider credentialsProvider = CredentialsProviderFactory.newSTSAssumeRoleSessionCredentialsProvider(
region, accessKeyId, accessKeySecret, roleArn);
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Create a ClientBuilderConfiguration instance.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf);
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance by using EcsRamRole
You can access OSS from an Elastic Compute Service (ECS) instance by using a RAM role attached to the instance. You can attach a RAM role to an ECS instance to access OSS from the instance by using temporary access credentials that are obtained from STS. The temporary access credentials are automatically generated and updated. Applications can obtain the temporary access credentials by using the instance metadata URL.
The following sample code provides an example on how to create an OSSClient instance by using EcsRamRole:
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Use ecs-ram-role to obtain temporary access credentials.
InstanceProfileCredentialsProvider credentialsProvider = CredentialsProviderFactory.newInstanceProfileCredentialsProvider("ecs-ram-role");
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, new ClientBuilderConfiguration());
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance in Apsara Stack or a private region
The following sample code provides an example on how to create an OSSClient instance in Apsara Stack or a private region:
// Specify the endpoint of the region in which the bucket is located.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create ClientBuilderConfiguration and change the default values of the parameters based on your business requirements.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Disable CNAME.
conf.setSupportCname(false);
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf);
// Shut down the OSSClient instance.
ossClient.shutdown();
Create an OSSClient instance by using an IP address
The following sample code provides an example on how to create an OSSClient instance by using an IP address:
// Specify an IP address as an endpoint in specific scenarios, such as scenarios that involve a private region. In specific scenarios, you must specify the IP address based on your business requirements.
String endpoint = "https://10.10.10.10";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create a ClientBuilderConfiguration instance.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Enable access from a second-level domain. By default, access from second-level domains is disabled. OSS SDK for Java 2.1.2 or later automatically detects IP addresses. If you use OSS SDK for Java whose version is earlier than 2.1.2, you must specify this parameter.
conf.setSLDEnabled(true);
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf);
// Shut down the OSSClient instance.
ossClient.shutdown();
Configure an OSSClient instance
ClientConfiguration is a configuration class of an OSSClient instance. You can use the ClientConfiguration class to configure parameters, such as the proxy, connection timeout period, and the maximum number of connections of the OSSClient instance.
The following sample code provides an example on how to specify parameters for an OSSClient instance by using the ClientConfiguration class:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create a ClientBuilderConfiguration instance.
// ClientBuilderConfiguration is a configuration class of an OSSClient instance. You can use the ClientBuilderConfiguration class to configure parameters, such as proxies, connection timeout period, and the maximum number of connections.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Specify the maximum number of HTTP connections allowed by an OSSClient instance. Default value: 1024.
conf.setMaxConnections(200);
// Specify User-Agent in the HTTP header. Default value: aliyun-sdk-java.
conf.setUserAgent("aliyun-sdk-java");
// Specify the IP address of the proxy server. Replace <yourProxyHost> with the IP address of the proxy server. Example: 196. xxx.xxx.
conf.setProxyHost("<yourProxyHost>");
// Specify the username verified by the proxy server. Replace <yourProxyUserName> with the username of the proxy server. Example: root.
conf.setProxyUsername("<yourProxyUserName>");
// Specify the password verified by the proxy server. Replace <yourProxyPassword> with the password of the user.
conf.setProxyPassword("<yourProxyPassword>");
// Create an OSSClient instance.
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(conf)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
The following table describes the common methods of the ClientConfiguration class.
Method | Description |
ClientConfiguration.setMaxConnections | The maximum number of HTTP connections that are allowed. Default value: 1024. |
ClientConfiguration.setSocketTimeout | The timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000. |
ClientConfiguration.setConnectionTimeout | The timeout period for establishing a connection. Unit: milliseconds. Default value: 50000. |
ClientConfiguration.setConnectionRequestTimeout | The timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, no timeout period is specified. |
ClientConfiguration.setIdleConnectionTime | The timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. Default value: 60000. Note |
ClientConfiguration.setSupportCname | Specifies whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. |
ClientConfiguration.setSLDEnabled | Specifies whether access from second-level domains is enabled. By default, access from second-level domains is disabled. |
ClientConfiguration.setProtocol | The protocol used to connect to OSS. Default value: HTTP. Valid values: HTTP and HTTPS. |
ClientConfiguration.setUserAgent | The user agent (the User-Agent field in the HTTP header). Default value: |
ClientConfiguration.setProxyHost | The IP address of the host that is used to access the proxy server. |
ClientConfiguration.setProxyPort | The port that is used to connect to the proxy server. |
ClientConfiguration.setProxyUsername | The username that is used to log on to the proxy server. |
ClientConfiguration.setProxyPassword | The password that is used to log on to the proxy server. |
ClientConfiguration.setRedirectEnable | Specifies whether to enable HTTP redirection. Note You can specify whether to enable HTTP redirection for OSS SDK for Java 3.10.1 or later. By default, HTTP redirection is enabled for OSS SDK for Java 3.10.1 or later. |
ClientConfiguration.setVerifySSLEnable | Specifies whether to enable SSL-based authentication. Note You can specify whether to enable SSL-based authentication for OSS SDK for Java 3.10.1 or later. By default, SSL-based authentication is enabled for OSS SDK for Java 3.10.1 or later. |
ClientConfiguration.setMaxErrorRetry | The maximum number of retries when a request error occurs. Default value: 3. Note When an error occurs, OSS uses different retry policies for different request types.
|
ClientConfiguration.setRetryStrategy() | // The custom retry policy. Generally, we recommend that you do not specify a custom retry policy. |