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.
For information about regions and endpoints supported by OSS, see Regions and endpoints.
For information about how to create an AccessKey pair for a Resource Access Management (RAM) user, see Create an AccessKey pair for a RAM user.
Use OSS SDK for Java 3.17.4 or later to support the V4 signature algorithm. For more information, see Install the SDK.
Prerequisites
Before you configure the client, you must configure the environment variables by using the AccessKey pair of a RAM user.
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
Run the following command to apply the changes:
source ~/.bashrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Run the following command in the terminal to view the default shell type:
echo $SHELL
Configure environment variables based on the default shell type.
ZshBashRun the following commands to add the configurations of the environment variables to the
~/.zshrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes:
source ~/.zshrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Run the following commands to add the configurations of the environment variables to the
~/.bash_profile
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
Run the following command to apply the changes:
source ~/.bash_profile
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
Run the following commands in PowerShell:
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Run the following commands to check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Default configuration examples
This section provides examples on how to use the V4 signature algorithm and the V1 signature algorithm to configure OSSClient instances.
Take note that the public endpoint of the bucket and the AccessKey pair of the RAM user are used in the following sample code.
Configuration examples for common scenarios
This section provides examples on how to use other types of endpoints to configure OSSClient instances. In the sample code, the V4 signature algorithm and the AccessKey pair of the RAM user are used.
Use an internal endpoint to configure an OSSClient instance
If your applications are deployed on an Elastic Compute Service (ECS) instance and you need to frequently access OSS data in a bucket in the same region as the ECS instance, use an internal endpoint to significantly reduce network latency and bandwidth costs.
The following sample code provides an example on how to use an internal endpoint to configure an OSSClient instance:
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-internal.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou-internal.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();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Use a custom domain name to configure an OSSClient instance
If you have multiple buckets for different usage, you can specify different subdomains for each bucket to better manage and organize resources.
The following sample code provides an example on how to use a custom domain name to configure an OSSClient instance:
You must first map the custom domain name to the default domain name of the bucket. Otherwise, an error is reported. For information about how to map a custom domain name to the default domain name of a bucket, 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. Example: https://static.example.com.
String endpoint = "https://static.example.com";
// Specify the region of the bucket. 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();
// Note: To enable CNAME, set this parameter to true.
clientBuilderConfiguration.setSupportCname(true);
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Use a private domain to configure an OSSClient instance
The following sample code provides an example on how to use a private domain to configure an OSSClient instance:
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 private domain. Example: https://service.corp.example.com.
String endpoint = "https://service.corp.example.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();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Use an IP address to configure an OSSClient instance
The following sample code provides an example on how to use an IP address to configure an OSSClient instance:
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 the endpoint 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();
}
}
Use a proxy server to configure an OSSClient instance
The following sample code provides an example on how to use a proxy server to configure an OSSClient instance:
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 the ClientBuilderConfiguration class.
// 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 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.128.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();
}
}
Configure a timeout period for an OSSClient instance
The following sample code provides an example on how to configure a timeout period for an OSSClient instance:
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 the ClientBuilderConfiguration class.
// 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 that are allowed. If you do not specify this parameter, the default value 1024 is used.
conf.setMaxConnections(1024);
// Specify the timeout period for data transmission at the socket layer. Unit: milliseconds. If you do not specify this parameter, the default value 50000 is used.
conf.setSocketTimeout(50000);
// Specify the timeout period for establishing a connection. Unit: milliseconds. If you do not specify this parameter, the default value 50000 is used.
conf.setConnectionTimeout(50000);
// Specify the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. If you do not specify this parameter, the timeout period is unlimited.
conf.setConnectionRequestTimeout(60*60*24*1000);
// Specify the timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. If you do not specify this parameter, the default value 60000 is used.
conf.setIdleConnectionTime(60000);
// 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();
}
}
Configuration methods of OSSClient instances
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 for the OSSClient instance.
Method | Description |
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. |
ClientConfiguration.setSupportCname | Specifies whether CNAME can be used as an endpoint. By default, CNAME can be used as an endpoint. |
ClientConfiguration.setCrcCheckEnabled | Specifies whether to enable cyclic redundancy check (CRC) verification. By default, CRC verification is enabled. |
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. 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. 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. When an error occurs, OSS uses different retry policies for different request types.
|
ClientConfiguration.setRetryStrategy() | The custom retry policy. In most cases, we recommend that you do not specify a custom retry policy. |