OSSClient is the Android client of Object Storage Service (OSS). OSSClient 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.

Note 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

Important 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:

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 a 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";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
// Create an OSSClient instance. 
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

Create an OSSClient instance based on Apsara Stack or a private region

The following code provides an example on how to create an OSSClient instance based on 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 STS. 
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 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 configure parameters such as proxy server, connection timeouts, and the maximum number of connections.

ParameterDescriptionMethod
maxConcurrentRequestThe maximum number of parallel requests. Default value: 5. ClientConfiguration.setMaxConcurrentRequest
socketTimeoutThe timeout period for data transmission at the Socket layer. Unit: milliseconds. Default value: 60000. ClientConfiguration.setSocketTimeout
connectionTimeoutThe timeout period for establishing a connection. Unit: milliseconds. Default value: 60000. ClientConfiguration.setConnectionTimeout
max_log_sizeThe maximum size of the log. Unit: MB. Default value: 5.ClientConfiguration.setMaxLogSize
maxErrorRetryThe maximum number of retry attempts when a request error occurs. Default value: 3. ClientConfiguration.setMaxErrorRetry
customCnameExcludeListSpecifies that CNAME resolution is skipped. ClientConfiguration.setCustomCnameExcludeList
proxyHostThe IP address that is used to access the proxy server. ClientConfiguration.setProxyHost
proxyPortThe port that is used to connect to the proxy server. ClientConfiguration.setProxyPort
mUserAgentMarkThe User-Agent field in the HTTP headers. ClientConfiguration.setUserAgentMark
httpDnsEnableSpecifies whether to enable HttpDNS.
  • true: enables HttpDNS. For OSSClient 2.9.12 and earlier, this is the default value.
  • false: disables HttpDNS. For OSSClient 2.9.12 and later, this is the default value.
ClientConfiguration.setHttpDnsEnable
checkCRC64Specifies whether to enable CRC-64. Default value: false. Valid values:
  • true: enables CRC-64.
  • false: disables CRC-64.
ClientConfiguration.setCheckCRC64
followRedirectsEnableSpecifies whether to enable HTTP redirection. Default value: false. Valid values:
  • true: enables HTTP redirection.
  • false: disables HTTP redirection.
ClientConfiguration.setFollowRedirectsEnable
okHttpClientSpecifies that a custom value can be configured for okHttpClient. ClientConfiguration.setOkHttpClient

The following code provides an example on how to configure 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. 
configuration.setMaxConcurrentRequest(3);
// Specify the timeout period for data transmission at the Socket layer. 
configuration.setSocketTimeout(50000);
// Specify a timeout period for establishing a connection. 
configuration.setConnectionTimeout(50000);
// Specify the maximum size of the log. 
configuration.setMaxLogSize(3 * 1024 * 1024);
// Specify the maximum number of retry attempts when a request error occurs. 
configuration.setMaxErrorRetry(3);
// Specify that CNAME resolution is skipped. 
List<String> cnameExcludeList = new ArrayList<>();
cnameExcludeList.add("cname");
configuration.setCustomCnameExcludeList(cnameExcludeList);
// Specify the IP address that is used to access the proxy server. 
configuration.setProxyHost("yourProxyHost");
// Configure the port for the proxy server.
configuration.setProxyPort(8080);
// Specify the User-Agent field in the HTTP header. 
configuration.setUserAgentMark("yourUserAgent");
// Specify whether to enable httpDns. 
configuration.setHttpDnsEnable(true);
// Specifies whether to enable CRC-64. 
configuration.setCheckCRC64(true);
// Specify whether to enable HTTP redirection. 
configuration.setFollowRedirectsEnable(true);
// Configure a custom 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 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.

// Specify the log format. 
// You can call OSSLog.enableLog() to enable logging and view logs in the OSS console. 
// The log can be written to the built-in SD card of the mobile phone in the following path: \OSSLog\logs.csv. By default, logging is disabled. 
// Logs record the request data, response data, and exception information in OSS operations. 
// Examples: the request ID and response headers. 
// 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 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();              
Note You can upload the logs to the server or to Alibaba Cloud Log Service.

Description of synchronous and asynchronous API operation calls

In mobile development scenarios, OSS SDK for Android provides synchronous and asynchronous calls for upload and download operations. Asynchronous calls are used for other operations.
  • Synchronous calls
    • After a synchronous operation is called, the call thread is blocked to obtain 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. ClientException indicates a local exception, such as a network exception and invalid parameters. ServiceException indicates service exceptions returned by OSS, such as authentication failures and server errors.
  • Asynchronous calls
    • A callback function must be configured for an asynchronous operation. The execution result of the request is handled in the callback function.
    • If exceptions occur in an asynchronous call, the exceptions are 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.