All Products
Search
Document Center

Object Storage Service:Initialization (Android SDK)

Last Updated:Nov 29, 2025

The OSSClient is the Android client for the OSS service. It provides methods to manage buckets and objects. Before you use the software development kit (SDK) to send requests to OSS, you must initialize an OSSClient instance and configure its settings.

Note

The lifecycle of the OSSClient must match the lifecycle of the application. Create a global OSSClient when the application starts, and destroy the OSSClient when the application ends.

Initialize OSSClient

Important

A mobile terminal is an untrusted environment. Storing the AccessKeyId and AccessKeySecret directly on the terminal to sign requests poses a high security threat. We recommend that you use the Security Token Service (STS) authentication mode or the self-signed mode.

You can create an OSSClient in one of the following ways.

Note

To learn how to call interfaces for operations such as uploads and downloads, see Quick Start (Android SDK).

The OSSClient initialization method for listing buckets is different from the general method shown in these examples. For more information, see List buckets (Android SDK).

Create an OSSClient using STS

The following code shows how to create an OSSClient using STS.

// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is 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);

Create an OSSClient using a custom domain name

The following code shows how to create an OSSClient using a custom domain name.

// Set yourEndpoint to the custom domain name.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is 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);

Create an OSSClient in an Apsara Stack or private domain environment

The following code shows how to create an OSSClient in an Apsara Stack or private domain environment.

// Set yourEndpoint to the Endpoint of the region where the bucket is located.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is 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 parsing.
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 OSSClient

ClientConfiguration is the configuration class for OSSClient. You can use this class to configure parameters such as the proxy, connection timeout, and maximum connections.

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, in milliseconds. Default value: 60000.

ClientConfiguration.setSocketTimeout

connectionTimeout

The timeout period for establishing a connection, in milliseconds. Default value: 60000.

ClientConfiguration.setConnectionTimeout

max_log_size

The size of the log file. Default value: 5 MB.

ClientConfiguration.setMaxLogSize

maxErrorRetry

The maximum number of retries after a request fails. Default value: 2.

ClientConfiguration.setMaxErrorRetry

customCnameExcludeList

Elements in the list will skip canonical name (CNAME) parsing.

ClientConfiguration.setCustomCnameExcludeList

proxyHost

The host address of the proxy server.

ClientConfiguration.setProxyHost

proxyPort

The port of the proxy server.

ClientConfiguration.setProxyPort

mUserAgentMark

The User-Agent header of HTTP in the user agent.

ClientConfiguration.setUserAgentMark

httpDnsEnable

Specifies whether to enable HTTPDNS.

  • true: HTTPDNS is enabled by default for versions earlier than 2.9.12.

  • false: HTTPDNS is disabled by default for versions 2.9.12 and later.

ClientConfiguration.setHttpDnsEnable

checkCRC64

Specifies whether to enable 64-bit cyclic redundancy check (CRC-64). Valid values:

  • true: Enables CRC-64.

  • false (default): Disables CRC-64.

ClientConfiguration.setCheckCRC64

followRedirectsEnable

Specifies whether to enable HTTP redirection. Valid values:

  • true: Enables HTTP redirection.

  • false (default): Disables HTTP redirection.

ClientConfiguration.setFollowRedirectsEnable

okHttpClient

A custom okHttpClient.

ClientConfiguration.setOkHttpClient

The following code shows how to use ClientConfiguration to configure OSSClient parameters.

// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";

ClientConfiguration configuration = new ClientConfiguration();
// Set the maximum number of concurrent requests. Default value: 5.
// configuration.setMaxConcurrentRequest(3);
// Set the timeout period for data transmission at the socket layer. Default value: 60s.
// configuration.setSocketTimeout(50000);
// Set the timeout period for establishing a connection. Default value: 60s.
// configuration.setConnectionTimeout(50000);
// Set the size of the log file. Default value: 5 MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);
// Set the maximum number of retries after a request fails. Default value: 2.
// configuration.setMaxErrorRetry(3);
// Elements in the list will skip CNAME parsing.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// The host address of the proxy server.
// configuration.setProxyHost("yourProxyHost");
// The port of the proxy server.
// configuration.setProxyPort(8080);
// The User-Agent header of HTTP in the user agent.
// configuration.setUserAgentMark("yourUserAgent");
// Specifies whether to enable cyclic redundancy check (CRC). Default value: false.
// configuration.setCheckCRC64(true);
// Specifies whether to enable HTTP redirection. Default value: false.
// configuration.setFollowRedirectsEnable(true);
// Set a custom 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

The mobile terminal environment is complex. The OSS SDK may not work correctly in some regions or during certain periods. To help developers locate issues, the OSS SDK records log information locally after the logging feature is enabled. To enable logging, you must initialize it before you use OSSClient. Call the method as follows.

// Log style.
// Call OSSLog.enableLog() to enable viewing logs in the console.
// You can write log files to the \OSSLog\logs.csv path on the phone's built-in SD card. This is disabled by default.
// Logs record request data, response data, and exception information for OSS operations.
// For example, requestId and response header.
// The following is a sample log record.
// Android version.
// android_version: 5.1  
// Android phone model.
// mobile_model: XT1085
// Network status.  
// network_state: connected
// Network connection type.
// network_type: WIFI 
// Specific operation behavior information.
// [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 files to your server or use Alibaba Cloud Simple Log Service to upload the log files.

Synchronous and asynchronous interfaces

The Android SDK provides both synchronous and asynchronous call examples for upload and download interfaces. This is because network requests are not allowed in the UI thread in mobile application development. For other interfaces, asynchronous call examples are the primary examples provided.

  • Synchronous call

    • A synchronous interface call blocks the thread until a result is returned.

    • Do not call synchronous interfaces in the UI thread.

    • When an exception occurs during a synchronous interface call, a ClientException or ServiceException is thrown directly. A ClientException indicates a local exception, such as a network connectivity issue or an invalid parameter. A ServiceException indicates a service error returned by OSS, such as an authentication failure or a server error.

  • Asynchronous call

    • For an asynchronous interface, you pass a callback function when making a request. The request result is processed in the callback.

    • When an exception occurs during an asynchronous request, the exception is handled in the callback function.

    • Calling an asynchronous interface directly returns a Task.

      OSSAsyncTask task = oss.asyncGetObejct(...);
      task.cancel(); // Cancel the task.
      task.waitUntilFinished(); // Wait until the task is complete.
      GetObjectResult result = task.getResult(); // Block the thread and wait for the result.