file

Java initialization

OSS Client is the Java client of OSS, which is used to manage OSS resources such as storage space and files. To initiate OSS requests using the Java SDK, you need to initialize an OSSClient instance and modify the default configuration items of ClientConfiguration as needed.

prerequisite

Before initializing the OSSClient, you need to configure access credentials. For details, see Configure Access Credentials

New OSSClient

important
  • OSSClient is thread safe, allowing multiple threads to access the same instance. You can reuse the same OSSClient instance according to business requirements, or create multiple OSSClient instances for separate use.

  • The OSS Client instance maintains a connection pool internally. When the OSSClient instance is no longer in use, please call the shutdown method to close it, so as to avoid creating too many OSSClient instances and causing resource exhaustion.

V4 signature (recommended)

The more secure V4 signature algorithm is recommended. When initializing with V4 signature, in addition to specifying the endpoint, you also need to specify the AliCloud universal region ID as the identifier of the region where the request originates. The example value is cn-hangzhou Also declare SignVersion V4. OSS Java SDK 3.17.4 and above supports V4 signature.

Take the V4 signature when creating an OSSClient using the OSS domain name as an example. For other scenarios of creating an OSSClient through a user-defined domain name, STS, etc., refer to the following examples to perform corresponding modifications.

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  String endpoint = " https://oss-cn-hangzhou.aliyuncs.com "; //Fill in the region information corresponding to the Endpoint, such as cn hangzhou. String region = "cn-hangzhou"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. 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(); //Close the OSSClient. ossClient.shutdown();

V1 signature (not recommended)

important

Alibaba Cloud Object Storage OSS will no longer open V1 signatures for new users (i.e. new UIDs) from December 1, 2024, and will stop updating and maintenance and no longer open V1 signatures for new buckets from June 1, 2025. Please switch to V4 signature as soon as possible to avoid affecting the service. For more information, see Announcement description

Create an OSSClient using the OSS domain name

The following code creates an OSSClient using the OSS domain name. For OSS domain names in different regions, see Access domain name and data center

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  String endpoint = "yourEndpoint"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider); //Close the OSSClient. ossClient.shutdown();

Create a new OSSClient using a custom domain name

The following code creates an OSSClient using a custom domain name. For more information about using a custom domain name to access OSS, see Bind the custom domain name to the bucket default domain name

important

The ossClient.listBuckets method cannot be used when using a custom domain name.

 //YourEndpoint fills in the custom domain name. String endpoint = "yourEndpoint"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create a ClientBuilderConfiguration instance, and you can modify the default parameters according to the actual situation. ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); //Set whether CNAME is supported. CNAME is used to bind a custom domain name to the target bucket. conf.setSupportCname(true); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider, conf); //Close the OSSClient. ossClient.shutdown();

Create an OSSClient using STS

The following code uses STS to create a new OSSClient.

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  String endpoint = "yourEndpoint"; //Obtain the access key (AccessKey ID and AccessKey Secret) and security token (SecurityToken) of STS from the environment variable as the access credential. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider); //Close the OSSClient. ossClient.shutdown();

Use STSAssumeRole to create a new OSSClient

The following code uses STSAssumeRole to create a new OSSClient.

 //The region that STSAssumeRole is authorized to access. Take East China 1 (Hangzhou) as an example. Please fill in other regions according to the actual situation. String region = "cn-hangzhou"; //Obtain the access key (AccessKeyId and AccessKeySecret) of the RAM user from the environment variable. Please configure the environment variables before running this code example. String accessKeyId = System.getenv("ALIYUN_ACCESS_KEY_ID"); String accessKeySecret = System.getenv("ALIYUN_ACCESS_KEY_SECRET"); //Get RamRoleArn of RAM role from environment variable. Please configure the environment variables before running this code example. String roleArn = System.getenv("ALIYUN_STS_ROLE_ARN");   //Create an instance of STSAssumeRoleSessionCredentialsProvider. STSAssumeRoleSessionCredentialsProvider credentialsProvider = CredentialsProviderFactory.newSTSAssumeRoleSessionCredentialsProvider( region, accessKeyId, accessKeySecret, roleArn); //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as 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); //Close the OSSClient. ossClient.shutdown();

Use EcsRamRole to create a new OSSClient

On ECS, you can access OSS through the instance RAM role. The instance RAM role allows you to associate a role with an ECS instance and access OSS within the instance based on the temporary voucher STS. Temporary vouchers are automatically generated and updated by the system. Applications can use the specified instance metadata URL to obtain temporary vouchers without special management.

The following code is used to create a new OSSClient using EcsRamRole.

 //Take East China 1 (Hangzhou) as an example. Please fill in other endpoints according to the actual situation. String endpoint = " https://oss-cn-hangzhou.aliyuncs.com ";      //Access credentials are obtained through ECS RAM roles. For example, take the role name (ecs ram role) access as an example. InstanceProfileCredentialsProvider credentialsProvider = CredentialsProviderFactory.newInstanceProfileCredentialsProvider("ecs-ram-role"); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, new ClientBuilderConfiguration()); //Close the OSSClient. ossClient.shutdown();

Create a new OSSClient in a VPC or VPC domain environment

The following code creates an OSSClient using a private cloud or a private domain environment.

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. String endpoint = "yourEndpoint"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create a ClientBuilderConfiguration instance, and you can modify the default parameters according to the actual situation. ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); //Turn off the CNAME option. conf.setSupportCname(false); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider, conf); //Close the OSSClient. ossClient.shutdown();

Create a new OSSClient using IP

The following code uses IP to create a new OSSClient.

 //In some special cases (such as private domain), you need to use the IP address as an endpoint. Please fill in according to the actual IP address. String endpoint = " https://10.10.10.10 "; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create ClientBuilderConfiguration. ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); //Enable the secondary domain name to access OSS. It is not enabled by default. The OSS Java SDK 2.1.2 and earlier versions need to set this value. The OSS Java SDK 2.1.2 and later versions will automatically detect the IP address, and do not need to set this value again. conf.setSLDEnabled(true); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider, conf); //Close the OSSClient. ossClient.shutdown();

Configure OSSClient

ClientConfiguration is the OSSClient configuration class. You can use this class to configure parameters such as proxy, connection timeout, and maximum number of connections. The parameters that can be set are as follows:

parameter

describe

method

MaxConnections

The maximum number of HTTP connections allowed to open. The default is 1024.

ClientConfiguration.setMaxConnections

SocketTimeout

The timeout of data transmission in the Socket layer (unit: milliseconds). The default is 50000 milliseconds.

ClientConfiguration.setSocketTimeout

ConnectionTimeout

The timeout for establishing a connection (in milliseconds). The default is 50000 milliseconds.

ClientConfiguration.setConnectionTimeout

ConnectionRequestTimeout

The timeout (in milliseconds) for getting a connection from the connection pool. The default is no timeout.

ClientConfiguration.setConnectionRequestTimeout

IdleConnectionTime

The connection idle timeout period. If the timeout period expires, the connection will be closed (unit: milliseconds). The default is 60000 milliseconds.

ClientConfiguration.setIdleConnectionTime

MaxErrorRetry

The maximum number of retries after a request fails. The default is 3 times.

ClientConfiguration.setMaxErrorRetry

SupportCname

Whether CNAME is supported as an endpoint. CNAME is supported by default.

ClientConfiguration.setSupportCname

SLDEnabled

Whether to enable the access mode of the second level domain. It is not enabled by default.

ClientConfiguration.setSLDEnabled

Protocol

The protocol (HTTP or HTTPS) used to connect to OSS. The default is HTTP.

ClientConfiguration.setProtocol

UserAgent

User agent refers to the User Agent header of HTTP. Default is aliyun-sdk-java

ClientConfiguration.setUserAgent

ProxyHost

Proxy server host address.

ClientConfiguration.setProxyHost

ProxyPort

Proxy server port.

ClientConfiguration.setProxyPort

ProxyUsername

The user name authenticated by the proxy server.

ClientConfiguration.setProxyUsername

ProxyPassword

Password verified by the proxy server.

ClientConfiguration.setProxyPassword

RedirectEnable

Whether to enable HTTP redirection.

explain

Java SDK 3.10.1 and above supports setting whether to enable HTTP redirection, which is enabled by default.

ClientConfiguration.setRedirectEnable

VerifySSLEnable

Whether to enable SSL certificate verification.

explain

Java SDK 3.10.1 and above supports setting whether to enable SSL certificate verification, which is enabled by default.

ClientConfiguration.setVerifySSLEnable

The following code is used to set OSSClient parameters using ClientConfiguration:

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  String endpoint = "yourEndpoint"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create ClientBuilderConfiguration. //ClientBuilderConfiguration is the OSSClient configuration class, which can configure parameters such as proxy, connection timeout, and maximum number of connections. ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); //Set the maximum number of HTTP connections that OSSClient allows to open. The default number is 1024. conf.setMaxConnections(200); //Set the timeout for data transmission in the Socket layer, which is 50000 milliseconds by default. conf.setSocketTimeout(10000); //Set the timeout for establishing a connection. The default is 50000 milliseconds. conf.setConnectionTimeout(10000); //Set the timeout time (in milliseconds) for getting connections from the connection pool. By default, it does not timeout. conf.setConnectionRequestTimeout(1000); //Set the connection idle timeout. If timeout occurs, the connection will be closed. The default is 60000 milliseconds. conf.setIdleConnectionTime(10000); //Set the number of failed request retries, which is 3 by default. conf.setMaxErrorRetry(5); //Set whether to support the custom domain name as the endpoint, which is supported by default. conf.setSupportCname(true); //Set whether to enable the access mode of the secondary domain name. It is not enabled by default. conf.setSLDEnabled(true); //Set the protocol (HTTP or HTTPS) used to connect to OSS. The default is HTTP. conf.setProtocol(Protocol. HTTP); //Set the user agent, which refers to the HTTP User Agent header. The default is aliyun sdk java. conf.setUserAgent("aliyun-sdk-java"); //To set the proxy server IP, please replace "<yourProxyHost>" with the IP address of the proxy server (such as "196.128. xxx. xxx"). conf.setProxyHost("<yourProxyHost>"); //To set the user name for proxy server authentication, please replace "<yourProxyUserName>" with the user name of the proxy server (such as "root"). conf.setProxyUsername("<yourProxyUserName>"); //To set the password for proxy server authentication, please replace "<yourProxyPassword>" with the user's authentication password. conf.setProxyPassword("<yourProxyPassword>"); //Set whether to enable HTTP redirection. It is enabled by default. conf.setRedirectEnable(true); //Set whether to enable SSL certificate verification. It is enabled by default. conf.setVerifySSLEnable(true); //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider, conf); //Close the OSSClient. ossClient.shutdown();

For more information, see AliCloud OSS Java SDK timeout settings

Retry Policy

When an exception occurs to a request, the OSS will adopt different default retry policies according to the request type.

  • When the request is of POST type, it is not retried by default.

  • When the request is of non POST type and meets any of the following conditions, OSS will retry according to the default retry policy. The maximum number of retries is 3.

    • When the exception is ClientException, the error code (errorCode) is ConnectionTimeout, SocketTimeout, ConnectionRefused, Unknown Host, and SocketException.

    • When the exception is OSSException, an error code other than InvalidResponse is returned.

    • The returned status codes are 500, 502, and 503.

When the default retry policy does not meet the use requirements, you can customize the retry policy and the maximum number of retries through the ClientConfiguration configuration class. It is generally not recommended to customize the retry policy. An example of a custom retry policy is as follows:

 //YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  String endpoint = "yourEndpoint"; //Get access credentials from environment variables. Please configure the environment variables before running this code example. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create ClientBuilderConfiguration. //ClientBuilderConfiguration is the configuration class of OSSClient, which can be used to configure parameters such as retry times, user-defined retry policies, and connection timeouts. ClientBuilderConfiguration conf= new ClientBuilderConfiguration(); //Set the number of failed request retries. The default value is 3. conf.setMaxErrorRetry(5); //Custom retry policy, generally not recommended. //Assuming that the TestRetryStrategy class is your customized retry policy, the TestRetryStrategy class needs to inherit RetryStrategy. conf.setRetryStrategy(new TestRetryStrategy()); //Create an OSSClient instance. OSS ossClient=new OSSClientBuilder().build(endpoint,  credentialsProvider, conf); //Close the OSSClient. ossClient.shutdown();

Next Steps

After initializing the OSSClient, you can use the OSSClient to initiate requests. For details, see quick get start

  • Introduction to this page (1)