Creating and Configuring an OBS Client (SDK for Java)
Scenarios
This section describes how to create and configure an OBS client. If you already have a client, skip this section and obtain the API details by referring to API Overview (SDK for Java).
Prerequisites
Ensure you have completed the following preparations:
- Select a proper SDK version by referring to Before You Start (SDK for Java).
- Prepare the service and development environments by referring to Preparations (SDK for Java).
- Download and install the OBS SDK for Java by referring to SDK Download and Installation (SDK for Java).
Important Notes
- Make sure to configure the client at the time you create it. After the client is created, you will not be able to configure it.
- If you use a temporary AK/SK pair, you can call ObsClient.refresh("yourAccessKey", "yourSecretKey", "yourSecurityToken") to refresh to keep the pair valid, without the need to create a new ObsClient instance.
- You are advised to create an ObsClient instance at the initialization and use it for the whole project. Creating multiple clients affects high-concurrency performance.
- ObsClient is thread-safe and can be used in concurrency scenarios.
- If a client is closed by calling ObsClient.close, it cannot be used again. To ensure the whole project uses only one client, you are advised not to proactively close the client.
Overview
You can select a client class, a method of obtaining access credentials, and other parameters by referring to Figure 1.
Category |
Option |
Description |
Sample Code |
---|---|---|---|
Client |
Client that does not transparently transmit access credentials |
If you want to configure access credentials only once and use them for all API calls, use ObsClient. |
|
Client that transparently transmits access credentials |
If you need to configure access credentials for each API call, use SecretFlexibleObsClient, which is inherited from ObsClient. |
||
Access credentials |
Passing access credentials as parameters |
Create an ObsClient instance and pass access credentials as parameters. |
|
Obtaining access credentials from environment variables |
Create an ObsClient instance and use EnvironmentVariableObsCredentialsProvider to obtain access credentials from environment variables. |
||
Obtaining access credentials from an agency in ECS scenarios |
Create an ObsClient instance and use EcsObsCredentialsProvider to automatically obtain temporary access credentials from the ECS. The access credentials are periodically updated automatically.
NOTICE:
|
||
Using a chain to search for access credentials |
You can use this method to search for access keys in a chain in a predefined sequence. The first pair of access keys obtained is used to create an ObsClient instance. By default, environment variables are checked first and then the ECS agencies are checked to obtain access credentials. You cannot customize the search method or sequence. |
||
Other configurations |
Configuring only the endpoint |
Other than access credentials, only the endpoint is configured. |
|
Configuring the endpoint and other parameters |
In addition to the endpoint, you need to configure the HTTP proxy, Socket timeout, and other parameters. You can use the ObsConfiguration class to configure the ObsClient instance. For details about the supported parameters, see Table 2. |
Code Examples
- Using the client class that does not transparently transmit access credentials to directly configure access credentials and configuring the endpoint
- Using permanent access keys (AKs/SKs)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // Create an ObsClient instance. ObsClient obsClient = new ObsClient(ak, sk, endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- Using temporary access credentials (AKs/SKs and security tokens)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); String securityToken = System.getenv("SECRET_TOKEN"); // Create an ObsClient instance. ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- BasicObsCredentialsProvider
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // Create an ObsClient instance. ObsClient obsClient = new ObsClient(new BasicObsCredentialsProvider(ak, sk), endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- Using permanent access keys (AKs/SKs)
- Using the SecretFlexibleObsClient client class that transparently transmits access credentials
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Create an instance of the ObsConfiguration class. ObsConfiguration config = new ObsConfiguration(); config.setEndPoint(endPoint); // Create an instance of SecretFlexibleObsClient. SecretFlexibleObsClient obsClient = new SecretFlexibleObsClient(config); // Use the instance of SecretFlexibleObsClient to access OBS. // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak1 = System.getenv("ACCESS_KEY_ID"); String sk1 = System.getenv("SECRET_ACCESS_KEY_ID"); obsClient.listBuckets(ak1, sk1); String ak2 = System.getenv("ACCESS_KEY_ID"); String sk2 = System.getenv("SECRET_ACCESS_KEY_ID"); obsClient.listBuckets(ak2, sk2); // Close the instance. obsClient.close();
- Using EnvironmentVariableObsCredentialsProvider to obtain access credentials from environment variables
In this method, you need to define OBS_ACCESS_KEY_ID and OBS_SECRET_ACCESS_KEY in the environment variables to represent the permanent AK and SK respectively.
1 2 3 4 5 6 7 8 9 10
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Create an ObsClient instance. ObsClient obsClient = new ObsClient(new EnvironmentVariableObsCredentialsProvider(), endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- Using EcsObsCredentialsProvider to obtain access credentials from an agency in the ECS scenarios
1 2 3 4 5 6 7 8 9 10
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Create an ObsClient instance. ObsClient obsClient = new ObsClient(new EcsObsCredentialsProvider(), endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- Using OBSCredentialsProviderChain to obtain access credentials from a chain
1 2 3 4 5 6 7 8 9 10
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Create an ObsClient instance. ObsClient obsClient = new ObsClient(new OBSCredentialsProviderChain(), endPoint); // Use the instance to access OBS. // Close the instance. obsClient.close();
- Using ObsConfiguration to configure parameters for the client
- KeyManagerFactory: By configuring KeyManagerFactory, you can save a certificate on your local PC and check whether the certificate returned by the server is correct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); String jksPassword = "you-jks-password"; String jksPath = "/path/to/your/keystore/file"; KeyStore ks = KeyStore.getInstance("JKS"); char[] passArray = jksPassword.toCharArray(); FileInputStream inputStream = new FileInputStream(jksPath); ks.load(inputStream, passArray); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, passArray); String trustJKSPassword = "you-trustJKS-password"; String trustJKSPath = "/path/to/your/trustKeyStore/file"; KeyStore trustKeyStore = KeyStore.getInstance("JKS"); char[] trustPassArray = trustJKSPassword.toCharArray(); FileInputStream trustInputStream = new FileInputStream(trustJKSPath); trustKeyStore.load(trustInputStream, trustPassArray); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustKeyStore); ObsConfiguration config = new ObsConfiguration(); config.setEndPoint(endPoint); config.setKeyManagerFactory(kmf); config.setTrustManagerFactory(tmf); ObsClient obsClient = new ObsClient(ak, sk, config);
The local certificate must be stored as a .jks file. You can run the following command to call the Java keytool to convert a .cer certificate into a .jks one:
keytool -import -file your-cer-file.cer -keystore your-keystore-file.jks
- HTTP proxy: After the HTTP proxy is configured, the SDK uses the proxy to access the server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Replace the following region with the one in use. EU-Dublin is used here as an example. String endPoint = "https://obs.eu-west-101.myhuaweicloud.com"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); String proxyUrl = "proxy.com"; int proxyPort = 8080; String proxyUser = "userName"; String proxyPassword = "password"; ObsConfiguration config = new ObsConfiguration(); config.setEndPoint(endPoint); config.setHttpProxy(proxyUrl, proxyPort, proxyUser, proxyPassword); ObsClient obsClient = new ObsClient(ak, sk,config);
- KeyManagerFactory: By configuring KeyManagerFactory, you can save a certificate on your local PC and check whether the certificate returned by the server is correct.
Configuring a User-Defined Domain Name to Access OBS
To learn how to configure a user-defined domain name, see Configuring a User-Defined Domain Name.
// Specify the user-defined domain name that has been configured on the console. String endPoint = "http://your-domain"; // Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // Create an instance of the ObsConfiguration class. ObsConfiguration config = new ObsConfiguration(); config.setEndPoint(endPoint); config.setCname(true); // Create an ObsClient instance. ObsClient obsClient = new ObsClient(ak, sk, config); // Create an instance of ObsClient using Provider. // ObsClient obsClient = new ObsClient(new EnvironmentVariableObsCredentialsProvider(), config); // ObsClient obsClient = new ObsClient(new EcsObsCredentialsProvider(), config); // Use the instance to access OBS. // Close the instance. obsClient.close();
ObsConfiguration Parameters
- If the network bandwidth is sufficient, you can tune the socketWriteBufferSize, sockeReadBufferSize, readBufferSize, and writeBufferSize parameters to improve upload and download performance.
- If the network condition is poor, you are advised to increase the values of connectionTimeout and socketTimeout.
Parameter |
Description |
Method |
Recommended Value |
---|---|---|---|
connectionTimeout |
Explanation: The amount of time to wait when initially establishing an HTTP/HTTPS connection before giving up and timing out. Default value: 60000, in milliseconds. |
ObsConfiguration.setConnectionTimeout |
[10000, 60000] |
socketTimeout |
Explanation: The amount of time to wait for data to be transferred by the socket layer before the transfer times out. Default value: 60000, in milliseconds. |
ObsConfiguration.setSocketTimeout |
[10000, 60000] |
idleConnectionTime |
Explanation: If the idle time of a connection exceeds the value of this parameter, the connection is closed. Default value: 30000, in milliseconds. |
ObsConfiguration.setIdleConnectionTime |
Configure this parameter based on your needs. |
maxIdleConnections |
Explanation: The allowed maximum number of pooled idle connections. Default value: 1000 |
ObsConfiguration.setMaxIdleConnections |
Configure this parameter based on your needs. |
maxConnections |
Explanation: The allowed maximum number of concurrent HTTP requests. Default value: 1000 |
ObsConfiguration.setMaxConnections |
Default |
maxErrorRetry |
Explanation: The allowed maximum number of retry attempts for failed requests (for example, request exceptions, or 500 or 503 error responses from the server). Restrictions: For object upload and download APIs, if an exception occurs when the data flow is being processed, the upload or download will not be retried. Default value: 3 |
ObsConfiguration.setMaxErrorRetry |
[0, 5] |
endPoint |
Explanation: OBS server address. It consists of a protocol type, domain name, and port number, for example, https://your-endpoint:443. For security purposes, you are advised to use HTTPS. Restrictions: Given the performance of DNS and reliability of OBS, you must set endPoint to a domain name, rather than an IP address. Default value: None |
ObsConfiguration.setEndPoint |
Configure this parameter based on your needs. |
httpProxy |
Explanation: HTTP proxy configuration. Default value: This parameter is left blank by default. |
ObsConfiguration.setHttpProxy |
Configure this parameter based on your needs. |
validateCertificate |
Explanation: Whether to verify the server certificate. Value range: true: The server certificate is verified. false: The server certificate is not verified. Default value: false |
ObsConfiguration.setValidateCertificate |
Configure this parameter based on your needs. |
verifyResponseContentType |
Explanation: Whether to verify the ContentType header in the response. Value range: true: The ContentType header is verified. false: The ContentType header is not verified. Default value: true |
ObsConfiguration.setVerifyResponseContentType |
Default |
readBufferSize |
Explanation: Size of the buffer used for downloading objects from socket streams. The value -1 indicates that no buffer is configured. Default value: -1, in bytes. |
ObsConfiguration.setReadBufferSize |
Configure this parameter based on your needs. |
writeBufferSize |
Explanation: Size of the buffer used for uploading objects to socket streams. The value -1 indicates that no buffer is configured. Default value: -1, in bytes. |
ObsConfiguration.setWriteBufferSize |
Configure this parameter based on your needs. |
socketWriteBufferSize |
Explanation: Size of the sending buffer of the socket. This parameter corresponds to java.net.SocketOptions.SO_SNDBUF. Default value: -1, in bytes, indicating that this parameter is not configured. |
ObsConfiguration.setSocketWriteBufferSize |
Default |
socketReadBufferSize |
Explanation: Size of the receiving buffer of the socket. This parameter corresponds to java.net.SocketOptions.SO_RCVBUF. Default value: -1, in bytes, indicating that this parameter is not configured. |
ObsConfiguration.setSocketReadBufferSize |
Default |
keyManagerFactory |
Explanation: Factory used for generating javax.net.ssl.KeyManager. Default value: This parameter is left blank by default. |
ObsConfiguration.setKeyManagerFactory |
Configure this parameter based on your needs. |
trustManagerFactory |
Explanation: Factory used for generating javax.net.ssl.TrustManager. Default value: This parameter is left blank by default. |
ObsConfiguration.setTrustManagerFactory |
Configure this parameter based on your needs. |
isStrictHostnameVerification |
Explanation: Whether to strictly verify the server-side host name. If this parameter is set to true, javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier needs to be used to create an object as an implementation of javax.net.ssl.HostnameVerifier to verify the host name. Value range: true: The host name of the server is strictly verified. false: The host name of the server is not strictly verified. Default value: false |
ObsConfiguration.setIsStrictHostnameVerification |
Configure this parameter based on your needs. |
keepAlive |
Explanation: Whether to use persistent connections to access OBS. Value range: true: Persistent connections are used. false: Persistent connections are not used. Default value: true |
ObsConfiguration.setKeepAlive |
Configure this parameter based on your needs. |
cname |
Explanation: Whether to use a user-defined domain name to access OBS. Value range: true: A user-defined domain name is used. false: A user-defined domain name is not used. Default value: false |
ObsConfiguration.setCname |
Configure this parameter based on your needs. |
sslProvider |
Explanation: Provider of the SSLContext. Default value: The SSLContext provided by the JDK is used. |
ObsConfiguration.setSslProvider |
Configure this parameter based on your needs. |
httpProtocolType |
Explanation: HTTP protocol type used for accessing the OBS server. Default value: HTTP1.1
NOTE:
If the value of endPoint does not contain any protocol, HTTPS is used by default. |
ObsConfiguration.setHttpProtocolType |
Configure this parameter based on your needs. |
httpDispatcher |
Explanation: User-defined dispatcher. Default value: None |
ObsConfiguration.setHttpDispatcher |
Configure this parameter based on your needs. |
secureRandom |
Explanation: User-defined random number generator. Default value: new SecureRandom()
NOTE:
|
ObsConfiguration.setSecureRandom |
Configure this parameter based on your needs. |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.