OSSClient for Android provides callers with various methods to manage buckets and objects in Object Storage Service (OSS). Before you use OSS SDK for Android to initiate a request to OSS, you must initialize and configure an OSSClient instance.
Make sure that the lifecycle of the OSSClient instance is the same as the lifecycle of the application for which the instance is created. This requires you to create an OSSClient instance when you start an application and release the instance when the application is stopped.
Initialize an OSSClient instance
A mobile device is used in various untrusted environments. Therefore, it is highly risky to store AccessKeyId
and AccessKeySecret
in a mobile device to sign requests. We recommend that you use the Security Token Service (STS) authentication mode or the self-signed mode.
You can use one of the following methods to create an OSSClient instance:
For more information about how to upload or download an object by calling an API operation, see Get started with OSS SDK for Android.
The method used to initialize an OSSClient instance for listing buckets is different from the method used in the following examples. For more information, see List buckets.
Use STS
The following sample code provides an example on how to create an OSSClient instance by using STS access credentials:
// 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";
// Specify the temporary AccessKey pair obtained from STS.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
String securityToken = "yourSecurityToken";
// 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 = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Use a custom domain name
The following sample code provides an example on how to create an OSSClient instance by using a custom domain name:
// Specify the custom domain name.
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";
// 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 = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Use Apsara Stack or a private endpoint
The following sample code provides an example on how to create an OSSClient instance in Apsara Stack or by using a private endpoint:
// Specify the endpoint of the region in which the bucket is located.
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";
// 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 = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration configuration = new ClientConfiguration();
// Skip CNAME resolution.
List<String> excludeList = new ArrayList<>();
excludeList.add(endpoint);
configuration.setCustomCnameExcludeList(excludeList);
// Create an OSSClient instance.
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(),endpoint, credentialProvider);
oss.setRegion(region);
Configure an OSSClient instance
ClientConfiguration is a configuration class of OSSClient. You can use ClientConfiguration to specify parameters, such as parameters for the proxy server, connection timeout period, and maximum number of connections. The following table describes the parameters.
Parameter | Description | Method |
maxConcurrentRequest | The maximum number of concurrent requests. Default value: 5. | ClientConfiguration.setMaxConcurrentRequest |
socketTimeout | The timeout period for data transmission at the Socket layer. Unit: milliseconds. Default value: 60000. | ClientConfiguration.setSocketTimeout |
connectionTimeout | The timeout period for establishing a connection. Unit: milliseconds. Default value: 60000. | ClientConfiguration.setConnectionTimeout |
max_log_size | The maximum size of a log. Unit: MB. Default value: 5. | ClientConfiguration.setMaxLogSize |
maxErrorRetry | The maximum number of retry attempts when a request error occurs. Default value: 2. | ClientConfiguration.setMaxErrorRetry |
customCnameExcludeList | A list of elements to skip CNAME resolution. | ClientConfiguration.setCustomCnameExcludeList |
proxyHost | The host of the proxy server. | ClientConfiguration.setProxyHost |
proxyPort | The port of the proxy server. | ClientConfiguration.setProxyPort |
mUserAgentMark | The HTTP User-Agent header. | ClientConfiguration.setUserAgentMark |
httpDnsEnable | Specifies whether to enable HTTPDNS.
| ClientConfiguration.setHttpDnsEnable |
checkCRC64 | Specifies whether to enable CRC-64. Valid values:
| ClientConfiguration.setCheckCRC64 |
followRedirectsEnable | Specifies whether to enable HTTP redirection. Valid values:
| ClientConfiguration.setFollowRedirectsEnable |
okHttpClient | Sets okhttpClient. | ClientConfiguration.setOkHttpClient |
The following sample code provides an example on how to specify 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";
// Specify the temporary AccessKey pair obtained from STS.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
String securityToken = "yourSecurityToken";
// 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 = "yourRegion";
ClientConfiguration configuration = new ClientConfiguration();
// Specify the maximum number of concurrent requests. Default value: 5.
// configuration.setMaxConcurrentRequest(3);
// Specify the timeout period for data transmission at the Socket layer. Default value: 60. Unit: seconds.
// configuration.setSocketTimeout(50000);
// Specify the timeout period for establishing a connection. Default value: 60. Unit: seconds.
// configuration.setConnectionTimeout(50000);
// Specify the maximum size of a log. Default value: 5. Unit: MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);
// Specify the maximum number of retries when a request error occurs. Default value: 2.
// configuration.setMaxErrorRetry(3);
// Specify that CNAME resolution is skipped for the elements in the list.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// Specify the host of the proxy server.
// configuration.setProxyHost("yourProxyHost");
// Specify the port of the proxy server.
// configuration.setProxyPort(8080);
// Specify the HTTP User-Agent header.
// configuration.setUserAgentMark("yourUserAgent");
// Specify whether to enable CRC-64. Default value: false.
// configuration.setCheckCRC64(true);
// Specify whether to enable HTTP redirection. Default value: false.
// configuration.setFollowRedirectsEnable(true);
// Set okHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(),endpoint, credentialProvider);
oss.setRegion(region);
Enable logging
Mobile devices are used in various environments. OSS SDK for Android may be unavailable in specific regions or during specific periods of time. To troubleshoot issues that may occur, you can enable logging to allow OSS SDK for Android to locally record logs. To enable logging, you must first initialize the OSSClient instance. The following sample code provides an example on how to enable logging.
// Specify the log style.
// Call OSSLog.enableLog() to enable logging. After logging is enabled, you can view logs in the OSS console.
// Write logs to the built-in SD card of the mobile phone in the following path: \OSSLog\logs.csv. By default, logs are not written to the path.
// Logs record the request data, response data, and exception information of OSS operations.
// Examples: the request ID and response headers.
// The following lines provide examples of log fields:
// The Android version.
// android_version: 5.1
// The Android mobile phone model.
// mobile_model: XT1085
// The network status.
// network_state: connected
// The type of the network connection.
// network_type: Wi-Fi
// The details of the operation.
// [2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid.
// A bucket name must:
// 1) be comprised of lower-case characters, numbers or dash(-);
// 2) start with lower case or numbers;
// 3) be between 3-63 characters long.
//------>end of log
// Call the following method to enable logging.
OSSLog.enableLog();
You can upload logs to the server or Simple Log Service.
Synchronous and asynchronous API calls
In mobile development scenarios, it is a best practice to avoid performing network operations on the UI thread. OSS SDK for Android provides synchronous and asynchronous calls for the upload and download operations. For most of the other operations, asynchronous calls are used.
Synchronous calls
After an operation is called synchronously, the code execution is blocked during the request until a response is returned.
Synchronous calls cannot be made on the UI thread.
If an exception occurs when you synchronously call an operation, the system throws a ClientException or ServiceException exception. A ClientException exception is a local exception, such as an invalid network parameter. A ServiceException exception is a service exception returned by OSS, such as an authentication failure or server error.
Asynchronous calls
A callback function must be configured for an asynchronous call. The execution result of the request is handled in the callback.
If an exception occurs in an asynchronous call, the exception is handled in the callback function.
When you asynchronously call an operation, the function returns a task.
OSSAsyncTask task = oss.asyncGetObejct(...); task.cancel(); // Cancel the task. task.waitUntilFinished(); // Wait until the task is complete. GetObjectResult result=task.getResult(); // Obtain the task result.