All Products
Search
Document Center

Object Storage Service:Initialize an OSSClient instance by using OSS SDK for Java

Last Updated:Mar 12, 2024

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

Prerequisites

Access credentials are configured. For more information, see Configure access credentials.

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.

Use the V1 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 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.

Important

If you use a custom domain name, the ossClient.listBuckets method is unavailable

// Specify the 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 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 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, see Authorized access.

// 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 that 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 ID and AccessKey secret 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 RamRoleArn of the RAM role from the environment variables. 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 ClientBuilderConfiguration. 
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. STS temporary access credentials are automatically generated and updated. Applications can obtain the STS 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 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:

// In specific scenarios, such as scenarios that involve a private region, an IP address is used as an endpoint. In these scenarios, you must specify the actual IP address. 
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 ClientBuilderConfiguration. 
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();                    

Use the V4 signature algorithm (recommended)

If you want to use the V4 signature algorithm, you must add the region of the endpoint to the OSSClient instance and set the signature version to SignVersion.V4 before initialization. The V4 signature algorithm is more secure than the V1 signature algorithm. OSS SDK for Java 3.17.4 and later support V4 signatures.

The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint and sign the request by using the V4 signature algorithm. To create an OSSClient instance by using a custom domain name or access credentials obtained from STS, you can refer to the following sample code and change the variables.

// 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 of the endpoint. 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();  

Configure an OSSClient instance

ClientConfiguration is a configuration class of an OSSClient instance. You can use ClientConfiguration to configure parameters, such as the proxy, connection timeout period, 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

The maximum number of HTTP connections that are allowed. Default value: 1024.

ClientConfiguration.setMaxConnections

SocketTimeout

The timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000.

ClientConfiguration.setSocketTimeout

ConnectionTimeout

The timeout period for establishing a connection. Unit: milliseconds. Default value: 50000.

ClientConfiguration.setConnectionTimeout

ConnectionRequestTimeout

The timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, the timeout period is unlimited.

ClientConfiguration.setConnectionRequestTimeout

IdleConnectionTime

The timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. Default value: 60000.

ClientConfiguration.setIdleConnectionTime

MaxErrorRetry

The maximum number of retries 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

The user agent (the User-Agent field in the HTTP header). Default value: aliyun-sdk-java.

ClientConfiguration.setUserAgent

ProxyHost

The IP address of the host that is used to access the proxy server.

ClientConfiguration.setProxyHost

ProxyPort

The port that is used to connect to the proxy server.

ClientConfiguration.setProxyPort

ProxyUsername

The username that is used to log on to the proxy server.

ClientConfiguration.setProxyUsername

ProxyPassword

The password that is used to log on to the proxy server.

ClientConfiguration.setProxyPassword

RedirectEnable

Specifies whether to enable HTTP redirection.

Note

You can configure 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.setRedirectEnable

VerifySSLEnable

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

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

// 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 ClientBuilderConfiguration. 
// ClientBuilderConfiguration is a configuration class of an OSSClient instance. You can use ClientBuilderConfiguration 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 the timeout period for data transmission at the socket layer. Unit: milliseconds. Default value: 50000. 
conf.setSocketTimeout(10000);
// Specify the timeout period for establishing a connection. Unit: milliseconds. Default value: 50000. 
conf.setConnectionTimeout(10000);
// Specify the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. By default, the timeout period is unlimited. 
conf.setConnectionRequestTimeout(1000);
// Specify the timeout period for idle connections. The connection is closed after the timeout period ends. Unit: milliseconds. Default value: 60000. 
conf.setIdleConnectionTime(10000);
// Specify the maximum number of retries when a request error occurs. Default value: 3. 
conf.setMaxErrorRetry(5);
// Specify whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. 
conf.setSupportCname(true);
// Specify whether access from second-level domains is enabled. By default, access from second-level domains is disabled. 
conf.setSLDEnabled(true);
// Specify the protocol used to connect to OSS. Valid values: HTTP and HTTPS. Default value: HTTP. 
conf.setProtocol(Protocol.HTTP);
// 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>");
// Specify whether to enable HTTP redirection. Default value: true. 
conf.setRedirectEnable(true);
// Specify whether to enable SSL-based authentication. Default value: true. 
conf.setVerifySSLEnable(true);

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, 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 based on the default retry policy for up to three times.

    • When the ClientException exception is reported, and one of the following error codes is returned: ConnectionTimeout, SocketTimeout, ConnectionRefused, UnknownHost, or SocketException.

    • When the OSSException exception is reported, and an error code except InvalidResponse is returned.

    • When the returned HTTP status code is 500, 502, or 503.

If the default retry policy cannot meet your business requirements, you can create a custom retry policy and configure the maximum number of retries by using the ClientConfiguration class. In most cases, we recommend that you do not create a custom retry policy. The following sample code provides an example on how to create a custom 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";

// 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. 
// ClientBuilderConfiguration is a configuration class of an OSSClient instance. You can use ClientBuilderConfiguration to specify the maximum number of retries, a custom retry policy, and the connection timeout period. 
ClientBuilderConfiguration conf= new ClientBuilderConfiguration();
// Specify the maximum number of retries 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 a custom retry policy. 
// For example, the TestRetryStrategy class is a retry policy that you specify. In this case, the TestRetryStrategy class must inherit RetryStrategy. 
conf.setRetryStrategy(new TestRetryStrategy());

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

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

What to do next

After you initialize an OSSClient instance, you can use the instance to initiate a request. For more information, see Get started with OSS SDK for Java.