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

To create an OSSClient instance, you must specify an endpoint. For more information about endpoints, see Regions and endpoints and Map a custom domain name.

  • Create the OSSClient instance based on an OSS endpoint

    The following code provides an example on how to create an OSSClient instance based on an OSS endpoint. OSSClient supports concurrent tasks. Therefore, a project can contain one or more OSSClient instances.

    // 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";
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a Resource Access Management (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:

    // Set yourEndpoint to the custom domain name. 
    String endpoint = "yourEndpoint";
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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. 
    ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
    // Configure whether CNAME is enabled. 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();                    
    Note 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:

    // Set yourEndpoint to the endpoint of the region in which the bucket is located. 
    String endpoint = "yourEndpoint";
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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. 
    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 some special scenarios such as a private region, an IP address is used as the endpoint. In such scenarios, specify the actual IP address. 
    String endpoint = "https://10.10.10.10";
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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. You must configure this parameter for OSS SDK for Java V2.1.2 or earlier, because versions later than 2.1.2 automatically detect IP addresses. 
    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 based on STS

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

    Note For more information about how to set up STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
    // 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";
    // 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. For other regions, specify this parameter based on the actual region. 
    String region = "cn-hangzhou";
    // Specify the AccessKey ID and AccessKey secret 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);
    // 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";
    // 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 a temporary credential 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 bound to the instance. You can bind a RAM role to an ECS instance to access OSS from the instance by using STS temporary credentials. STS temporary credentials are automatically generated and updated. Applications can obtain the STS temporary 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 China (Hangzhou) region is used. For other regions, specify the endpoint of the actual region. 
    String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";     
    
    // Use EcsRamRole to obtain the access credential. The following code shows how to obtain the access credential 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.

Parameter Description Method
MaxConnections Specifies the maximum number of HTTP connections that are allowed. Default value: 1024. ClientConfiguration.setMaxConnections
SocketTimeout Specifies the timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000. ClientConfiguration.setSocketTimeout
ConnectionTimeout Specifies the timeout period for establishing a connection. Unit: milliseconds. Default value: 50000. ClientConfiguration.setConnectionTimeout
ConnectionRequestTimeout Specifies the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, the timeout period is unlimited. ClientConfiguration.setConnectionRequestTimeout
IdleConnectionTime Specifies the timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. Default value: 60000. ClientConfiguration.setIdleConnectionTime
MaxErrorRetry Specifies the maximum number of retry attempts that are allowed when a request error occurs. Default value: 3. ClientConfiguration.setMaxErrorRetry
SupportCname Specifies whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. ClientConfiguration.setSupportCname
SLDEnabled Specifies whether access from second-level domains is enabled. By default, access from second-level domains is disabled. ClientConfiguration.setSLDEnabled
Protocol The protocol used to connect to OSS. Default value: HTTP. Valid values: HTTP and HTTPS. ClientConfiguration.setProtocol
UserAgent Specifies the user agent (the User-Agent field in the HTTP header). Default value: aliyun-sdk-java. ClientConfiguration.setUserAgent
ProxyHost Specifies the IP address to access the proxy host. ClientConfiguration.setProxyHost
ProxyPort Specifies the port for the proxy server. ClientConfiguration.setProxyPort
ProxyUsername Specifies the username verified by the proxy server. ClientConfiguration.setProxyUsername
ProxyPassword Specifies the password verified by the proxy server. ClientConfiguration.setProxyPassword
RedirectEnable Specifies 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
VerifySSLEnable Specifies 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";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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:
// 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";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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 customize retry policies and configure parameters such as retry times and the connection timeout period. 
ClientConfiguration conf= new ClientConfiguration();
// Configure the maximum number of allowed retry attempts when a request error occurs. Default value: 3. 
conf.setMaxErrorRetry(5);
// Customize a retry policy. Generally, we recommend that you do not customize retry policies. 
// Assume that the TestRetryStrategy class is a retry policy that you customized. Then, 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();