OSSClient is the Android client of Object Storage Service (OSS). OSSClient provides callers with a various methods to manage buckets and objects. 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.
Create an OSSClient instance by using STS
The following code provides an example on how to create an OSSClient instance by using STS:
// 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. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
String securityToken = "yourSecurityToken";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
Create an OSSClient instance by using a custom domain name
The following 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. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
String securityToken = "yourSecurityToken";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
Create an OSSClient instance in Apsara Stack or a private region
The following 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";
// Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
String securityToken = "yourSecurityToken";
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.
OSSClient oss = new OSSClient(getApplicationContext(),endpoint, credentialProvider, configuration);
Create an OSSClient instance by using the self-signed mode
The following code provides an example on how to create an OSSClient instance by using the self-signed mode:
// 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";
OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
@Override
public String signContent(String content) {
// Sign the content. signature is the signed string.
String signature = "signature";
return signature;
}
};
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
For more information about the self-signed mode, see Self-signed mode.
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 parallel 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 retries when a request error occurs. Default value: 3. | ClientConfiguration.setMaxErrorRetry |
customCnameExcludeList | Specifies that CNAME resolution is skipped. | ClientConfiguration.setCustomCnameExcludeList |
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 |
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 | Specifies that a custom value can be configured for okHttpClient. | ClientConfiguration.setOkHttpClient |
The following 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";
ClientConfiguration configuration = new ClientConfiguration();
// Specify the maximum number of parallel 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.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// Specify the IP address of the host that is used to access the proxy server.
// configuration.setProxyHost("yourProxyHost");
// Specify the port that is used to connect to 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);
// Specify a custom value for okHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(),endpoint, credentialProvider, configuration);
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 code provides an example on how to initialize the OSSClient instance.
// Specify the log style.
// Call OSSLog.enableLog() to enable logging and 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 cannot be 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 section provides an example of the data in a log:
// 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 operations.
// [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 this method to enable logging.
OSSLog.enableLog();
You can upload the logs to the server or Simple Log Service.
Synchronous and asynchronous API calls
In mobile development scenarios, 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 a synchronous operation is called, the call is blocked from returning the response.
The operations that are synchronously called cannot be called in the UI thread.
If an exception occurs when you call a synchronous operation, the system throws a ClientException or ServiceException exception. A ClientException exception specifies a local exception, such as an invalid network parameter. A ServiceException exception specifies a service exception returned by OSS, such as authentication failure and server error.
Asynchronous calls
A callback function must be configured for an asynchronous operation. 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 call an asynchronous 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.