OSSClient is the Android client of Object Storage Service (OSS). It provides callers with a series of 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.
Obtain an endpoint
An endpoint is a URL used to access Alibaba Cloud OSS in a specific region. The following types of endpoints are supported:
- OSS endpoint
You can query the endpoint of the region in which your bucket is located in one of the following ways:
- For more information about how to query the endpoint of a region, see Regions and endpoints.
- Log on to the OSS console and query the endpoint of the region in which your bucket is located by performing
the following steps: On the Overview page of the bucket, view the URL that can be
used to access the bucket over the Internet. The string that starts with oss-cn in
the URL is the endpoint of the bucket. For example, if the URL of a bucket is
examplebucket.oss-cn-hangzhou.aliyuncs.com, the endpoint of region in which the bucket is located is
- Custom domain names
You can add a CNAME record to map a custom domain name to a bucket. Then, you can use the custom domain name to access objects in the bucket.
For example, if you want to map the
example.aliyundoc.comdomain name to a bucket named examplebucket in the China (Hangzhou) region, you must contact your DNS provider of
aliyundoc.comto configure a new CNAME record. This record is used to resolve
Configure an endpoint and credentials
A mobile device is used in various untrusted environments. Therefore, it is highly
risky to store
AccessKeySecret in a mobile device to sign requests. We recommend that you use the credentials obtained
from Security Token Service (STS) or a signed URL to access OSS.
For more information about STS authentication mode and self-signed mode, see Authorized access.
For more information about the demo project, visit GitHub.
The following code provides an example on how to configure the endpoint and CredentialProvider parameters.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Enter the endpoint of an STS application server. String stsServer = "https://example.com" // We recommend that you use OSSAuthCredentialsProvider. The token is automatically updated after the token expires. OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer); // If you do not configure other parameters, the default values are used. ClientConfiguration conf = new ClientConfiguration(); conf.setConnectionTimeout(15 * 1000); // The connection timeout period. Unit: seconds. Default value: 15. conf.setSocketTimeout(15 * 1000); // The socket timeout period. Unit: seconds. Default value: 15. conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. Default value: 5. conf.setMaxErrorRetry(2); // The maximum number of retries. Default value: 2. OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
Set the endpoint to a custom domain name
If a custom domain name is mapped to the bucket, set the endpoint to the custom domain name.
String endpoint = "https://example.aliyundoc.com"; ... OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
Mobile devices are used in various environments. OSS SDK for Android is 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 record logs in the local client. To enable logging, you must initialize the OSSClient instance before you use the instance. The following code provides an example on how to initialize the OSSClient instance.
// The style of the log. // You can call OSSLog.enableLog() to enable logging and view logs in the console. // The log file can be written in the built-in SD card of the mobile phone in the path \OSSLog\logs.csv. By default, logging is disabled. // Logs record the request data, returned data, and exception information in OSS operations. // Examples: the request ID and response header. // The following section provides an example of the data in the log file: // 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 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 logs to the server to track issues.
- You can also upload logs to Alibaba Cloud Log Service. For more information, see Log Service.
Configure network parameters
The following code provides an example on how to configure ClientConfiguration during the initialization process:
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // If you use a mobile device, we recommend that you use STS to initialize the OSSClient instance. OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>"); ClientConfiguration conf = new ClientConfiguration(); conf.setConnectionTimeout(15 * 1000); // The connection timeout period. Unit: seconds. Default value: 15. conf.setSocketTimeout(15 * 1000); // The socket timeout period. Unit: seconds. Default value: 15. conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. Default value: 5. conf.setMaxErrorRetry(2); // The maximum number of retries. Default value: 2. OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
Description of synchronous and asynchronous API operation calls
Network requests cannot be processed in the UI thread in mobile development. Therefore, most operations in OSS SDK for Android support synchronous and asynchronous calls. When an operation is synchronously called, the operation blocks other requests and waits for the returned results. When an API operation is asynchronously called, the operation imports a callback function that processes the results of the request.
The operations that are synchronously called cannot be called in the UI thread. If exceptions occur in a synchronous call, a ClientException or ServiceException exception is thrown. The ClientException exception indicates local exceptions such as network exceptions and invalid parameters. The ServiceException exception indicates service exceptions returned by OSS, such as authentication failures and server errors.
If exceptions occur in an asynchronous call, the exceptions are handled in the callback function.
When an operation is asynchronously called, the function directly returns a task. You can cancel the task, wait until the task is completed, or directly obtain the task result. Example:
OSSAsyncTask task = oss.asyncGetObejct(...); task.ca ncel(); // Cancel the task. task.waitUntilFinished(); // Wait until the task is completed. GetObjectResult result=task.getResult(); // Directly obtain the task result.
Specify whether to enable the DNS settings
ClientConfiguration conf = new ClientConfiguration(); conf.setHttpDnsEnable(true);// The default value is true, which indicates that the DNS settings is enabled. To disable the DNS settings, set conf.setHttpDnsEnable to false.
Configure a custom user-agent
ClientConfiguration conf = new ClientConfiguration(); // By default, the custom user-agent is added at the end of the SDK by default. conf.setUserAgentMark("customUserAgent");