OSSClient serves as the Java client to manage Object Storage Service (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 ClientConfiguration.

Create an OSSClient instance

Important
  • 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.
  • To create an OSSClient instance, you must specify an endpoint. For more information about endpoints, see Regions and endpoints.

You can use one of the following methods to create an OSSClient:

Create an OSSClient instance by using an OSS endpoint

The following code provides an example on how to create an OSSClient instance by using an OSS endpoint.

// 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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// Shut down the OSSClient instance. 
ossClient.shutdown();                    

Create an OSSClient instance by using a custom domain name

The following code provides an example on how to create an OSSClient instance by using a custom domain name.

For more information about how to use a custom domain name to access OSS, see Map custom domain names.

// Set yourEndpoint to the custom domain name that you want to use. 
String endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create a ClientConfiguration instance and modify the default 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, accessKeyId, accessKeySecret, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();                    
Important ossClient.listBuckets is unavailable when a custom domain name is used.

Create an OSSClient instance based on Apsara Stack or a private region

The following code provides an example on how to create an OSSClient instance based on Apsara Stack or a private region:

// Specify the endpoint of the region in which the bucket is located. 
String endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create a ClientConfiguration instance and modify the default 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, accessKeyId, accessKeySecret, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();                    

Create an OSSClient instance based on an IP address

The following code provides an example on how to create an OSSClient instance based on an IP address:

// In special cases, such as cases that involve a private region, an IP address is used as an endpoint. In these cases, you must specify the actual IP address. 
String endpoint = "https://10.10.10.10";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create a ClientConfiguration instance. 
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Enable access from a second-level domain because access from a second-level domain is disabled by default. OSS SDK for Java V2.1.2 or later automatically detects IP addresses. If you use OSS SDK for Java whose version is earlier than V2.1.2, you must configure this parameter. 
conf.setSLDEnabled(true);

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();                    

Create an OSSClient instance by using STS

The following code provides an example on how to create an OSSClient instance by using Security Token Service (STS):

Note For more information about how to configure STS, see Use temporary 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. The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The unit of the validity period of temporary access credentials is 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.
// 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";
// Specify the temporary AccessKey pair obtained from STS. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
String securityToken = "yourSecurityToken";

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

// Shut down the OSSClient instance. 
ossClient.shutdown();                    

For more information, see Authorized access.

Create an OSSClient instance by using STSAssumeRole

The following code provides an example on how to create an OSSClient by using STSAssumeRole:

// Specify the region that STSAssumeRole can access. In this example, the China (Hangzhou) region is used. Specify this parameter based on the actual region. 
String region = "cn-hangzhou";
// Specify the AccessKey pair of the RAM user. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the Alibaba Cloud Resource Name (ARN) of STSAssumeRole, which indicates the ID of the role. Format: acs:ram::$accountID:role/$roleName. 
// $accountID indicates the Alibaba Cloud account ID. To view the Alibaba Cloud account ID, perform the following steps: Log on to the OSS console, and move the pointer over the profile picture in the upper-right corner to view and copy the account ID, or click Basic Information to view the account ID. 
// $roleName indicates the name of the RAM role. To view the RAM role name, perform the following steps: Log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the page that appears, view the name in the Role Name column. 
String roleArn = "acs:ram::17464958********:role/ossststest";   
// Create an STSAssumeRoleSessionCredentialsProvider instance. 
STSAssumeRoleSessionCredentialsProvider provider = 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 ClientConfiguration instance. 
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();

 
// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, provider, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();

For more information, see Use temporary credentials provided by STS to access OSS.

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. STS temporary access credentials are automatically generated and updated. Applications can obtain STS temporary access credentials by using the instance metadata URL.

The following code provides an example on how to create an OSSClient by using EcsRamRole:

// Use the EcsRamRole role to access OSS. 
// 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 EcsRamRole to obtain temporary access credentials. The following code shows how to obtain temporary access credentials by using a role named ecs-ram-role. 
InstanceProfileCredentialsProvider provider = CredentialsProviderFactory.newInstanceProfileCredentialsProvider("ecs-ram-role");

// Create an OSSClient instance. 
 OSS ossClient = new OSSClientBuilder().build(endpoint, provider, new ClientBuilderConfiguration());

// Shut down the OSSClient instance. 
ossClient.shutdown(); 

Configure an OSSClient instance

ClientConfiguration is a configuration class of OSSClient. You can use ClientConfiguration to configure parameters such as host proxies, connection timeouts, and the maximum number of connections. The following table describes the parameters that you can configure when you configure an OSSClient instance.

ParameterDescriptionMethod
MaxConnectionsSpecifies the maximum number of HTTP connections that are allowed. Default value: 1024. ClientConfiguration.setMaxConnections
SocketTimeoutSpecifies the timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000. ClientConfiguration.setSocketTimeout
ConnectionTimeoutSpecifies the timeout period for establishing a connection. Unit: milliseconds. Default value: 50000. ClientConfiguration.setConnectionTimeout
ConnectionRequestTimeoutSpecifies the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, the timeout period is unlimited. ClientConfiguration.setConnectionRequestTimeout
IdleConnectionTimeSpecifies the timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. Default value: 60000. ClientConfiguration.setIdleConnectionTime
MaxErrorRetrySpecifies the maximum number of retry attempts that are allowed when a request error occurs. Default value: 3. ClientConfiguration.setMaxErrorRetry
SupportCnameSpecifies whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. ClientConfiguration.setSupportCname
SLDEnabledSpecifies whether access from second-level domains is enabled. By default, access from second-level domains is disabled. ClientConfiguration.setSLDEnabled
ProtocolThe protocol used to connect to OSS. Default value: HTTP. Valid values: HTTP and HTTPS. ClientConfiguration.setProtocol
UserAgentSpecifies the user agent (the User-Agent field in the HTTP header). Default value: aliyun-sdk-java. ClientConfiguration.setUserAgent
ProxyHostSpecifies the IP address to access the proxy host. ClientConfiguration.setProxyHost
ProxyPortSpecifies the port for the proxy server. ClientConfiguration.setProxyPort
ProxyUsernameSpecifies the username verified by the proxy server. ClientConfiguration.setProxyUsername
ProxyPasswordSpecifies the password verified by the proxy server. ClientConfiguration.setProxyPassword
RedirectEnableSpecifies whether HTTP redirection is enabled.
Note You can configure whether HTTP redirection is enabled for OSS SDK for Java V3.10.1 or later. By default, HTTP redirection is enabled for OSS SDK for Java V3.10.1 or later.
ClientConfiguration.setRedirectEnable
VerifySSLEnableSpecifies whether SSL-based authentication is enabled.
Note You can configure whether SSL-based authentication is enabled for OSS SDK for Java V3.10.1 or later. By default, SSL-based authentication is enabled for OSS SDK for Java V3.10.1 or later.
ClientConfiguration.setVerifySSLEnable

The following code provides an example on how to configure parameters for an OSSClient instance by using ClientConfiguration:

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
String endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create a ClientConfiguration instance. ClientConfiguration is a configuration class of OSSClient. You can use ClientConfiguration to configure parameters such as host proxies, connection timeouts, and the maximum number of connections. 
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();

// Configure the maximum number of HTTP connections allowed by an OSSClient instance. Default value: 1024. 
conf.setMaxConnections(200);
// Configure the timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000. 
conf.setSocketTimeout(10000);
// Configure the timeout period for establishing a connection. Unit: milliseconds. Default value: 50000. 
conf.setConnectionTimeout(10000);
// Configure the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, the timeout period is unlimited. 
conf.setConnectionRequestTimeout(1000);
// Configure the timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. Default value: 60000. 
conf.setIdleConnectionTime(10000);
// Configure the maximum number of allowed retry attempts when a request error occurs. Default value: 3. 
conf.setMaxErrorRetry(5);
// Configure whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. 
conf.setSupportCname(true);
// Configure whether access from second-level domains is enabled. By default, access from second-level domains is disabled. 
conf.setSLDEnabled(true);
// Configure the protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. 
conf.setProtocol(Protocol.HTTP);
// Configure User-Agent in the HTTP header. Default value: aliyun-sdk-java. 
conf.setUserAgent("aliyun-sdk-java");
// Configure the port for the proxy host. 
conf.setProxyHost("<yourProxyHost>");
// Configure the username verified by the proxy host. 
conf.setProxyUsername("<yourProxyUserName>");
// Configure the password verified by the proxy host. 
conf.setProxyPassword("<yourProxyPassword>");
// Configure whether HTTP redirection is enabled. By default, HTTP redirection is enabled. 
conf.setRedirectEnable(true);
// Configure whether SSL-based authentication is enabled. By default, SSL-based authentication is enabled. 
conf.setVerifySSLEnable(true);

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();
            

Retry policies

When an error occurs, OSS uses different retry policies for different request types.
  • If a request is a POST request, OSS does not retry the request by default.
  • If a non-POST request matches one of the following scenarios, OSS retries the request by based on the default retry policy. OSS retries three times at most.
    • The exception is ClientException and the returned error code is ConnectionTimeout, SocketTimeout, ConnectionRefused, UnknownHost, or SocketException.
    • The exception is OSSException, and the returned error code is not InvalidResponse.
    • The returned status code is 500, 502, or 503.
If the default retry policy cannot meet your requirements, you can customize a retry policy and the maximum number of retries by using the ClientConfiguration class. Generally, we recommend that you do not customize retry policies. The following code provides an example on how to customize a retry policy:
// 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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";

// Create a ClientConfiguration instance. 
// ClientConfiguration is a configuration class of OSSClient. ClientConfiguration can be used to specify custom retry policies and configure parameters such as retry times and the connection timeout period. 
ClientBuilderConfiguration conf= new ClientBuilderConfiguration();
// Specify the maximum number of allowed retry attempts when a request error occurs. Default value: 3. 
conf.setMaxErrorRetry(5);
// Specify a custom retry policy. In most cases, we recommend that you do not specify custom retry policies. 
// For example, you specified the TestRetryStrategy class as a retry policy and the TestRetryStrategy class must inherit RetryStrategy. 
conf.setRetryStrategy(new TestRetryStrategy());

// Create an OSSClient instance. 
OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);

// Shut down the OSSClient instance. 
ossClient.shutdown();