All Products
Search
Document Center

Object Storage Service:Initialization (Android SDK)

Last Updated:Mar 20, 2026

OSSClient is the Android client for OSS. It provides methods to manage buckets and objects. Initialize an OSSClient instance and configure its settings before sending any requests to OSS.

Important

A mobile device is an untrusted environment. Storing AccessKeyId and AccessKeySecret directly on the device poses a serious security risk. Use Security Token Service (STS) authentication or the self-signed mode instead.

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

Initialize OSSClient

OSSClient requires a credential provider (OSSCredentialProvider) that handles authentication. This decouples credential management from the client, so you can rotate or refresh credentials without re-creating the client.

Choose the initialization method that matches your environment:

For upload and download examples, see Quick Start (Android SDK). The OSSClient initialization method for listing buckets differs from the examples below. See List buckets (Android SDK).

Create an OSSClient using STS

Use this method for production apps. STS issues temporary credentials that expire automatically, limiting the impact of any credential exposure.

// Replace <your-endpoint> with the endpoint for the region where your bucket is located.
// Example: https://oss-cn-hangzhou.aliyuncs.com
String endpoint = "<your-endpoint>";

// Temporary credentials obtained from STS
String accessKeyId = "<your-sts-access-key-id>";
String accessKeySecret = "<your-sts-access-key-secret>";
String securityToken = "<your-sts-security-token>";

// Replace <your-region> with the region ID. Example: cn-hangzhou
String region = "<your-region>";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);

ClientConfiguration config = new ClientConfiguration();
// Set the request signing version to Signature Version 4 (V4).
config.setSignVersion(SignVersion.V4);

OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Replace the following placeholders:

PlaceholderDescriptionExample
<your-endpoint>Endpoint for the region where your bucket is locatedhttps://oss-cn-hangzhou.aliyuncs.com
<your-sts-access-key-id>Temporary AccessKey ID from STSSTS.NUg...
<your-sts-access-key-secret>Temporary AccessKey secret from STS3D4L...
<your-sts-security-token>Security token from STSCAIS...
<your-region>Region ID where your bucket is locatedcn-hangzhou

Create an OSSClient using a custom domain name

Use this method when accessing OSS through a custom domain (CNAME).

// Replace <your-custom-domain> with your custom domain name.
String endpoint = "<your-custom-domain>";

// Temporary credentials obtained from STS
String accessKeyId = "<your-sts-access-key-id>";
String accessKeySecret = "<your-sts-access-key-secret>";
String securityToken = "<your-sts-security-token>";

// Replace <your-region> with the region ID. Example: cn-hangzhou
String region = "<your-region>";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);

ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);

OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Create an OSSClient in an Apsara Stack or private domain environment

In Apsara Stack and private domain environments, add the endpoint to the CNAME exclude list to skip CNAME resolution.

// Replace <your-endpoint> with the endpoint provided by your Apsara Stack or private domain environment.
String endpoint = "<your-endpoint>";

// Temporary credentials obtained from STS
String accessKeyId = "<your-sts-access-key-id>";
String accessKeySecret = "<your-sts-access-key-secret>";
String securityToken = "<your-sts-security-token>";

// Replace <your-region> with the region ID. Example: cn-hangzhou
String region = "<your-region>";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);

ClientConfiguration configuration = new ClientConfiguration();
// Skip CNAME resolution for this endpoint.
List<String> excludeList = new ArrayList<>();
excludeList.add(endpoint);
configuration.setCustomCnameExcludeList(excludeList);
configuration.setSignVersion(SignVersion.V4);

OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Configure OSSClient

ClientConfiguration lets you tune connection behavior, retries, logging, and more. All parameters are optional — the defaults work for most apps.

ParameterDescriptionDefault
maxConcurrentRequestMaximum number of concurrent requests5
socketTimeoutSocket-layer data transmission timeout (ms)60000
connectionTimeoutConnection establishment timeout (ms)60000
max_log_sizeMaximum log file size5 MB
maxErrorRetryMaximum retries after a request fails2
customCnameExcludeListEndpoints that skip CNAME resolution
proxyHostProxy server host address
proxyPortProxy server port
mUserAgentMarkCustom string appended to the HTTP User-Agent header
httpDnsEnableWhether to enable HTTPDNS. true by default for versions earlier than 2.9.12; false by default for versions 2.9.12 and laterVersion-dependent
checkCRC64Whether to enable 64-bit cyclic redundancy check (CRC-64) verificationfalse
followRedirectsEnableWhether to follow HTTP redirectsfalse
okHttpClientCustom OkHttpClient instance

The following example shows how to apply a custom ClientConfiguration. Uncomment and adjust any settings you need.

String endpoint = "<your-endpoint>";
String accessKeyId = "<your-sts-access-key-id>";
String accessKeySecret = "<your-sts-access-key-secret>";
String securityToken = "<your-sts-security-token>";
String region = "<your-region>";

ClientConfiguration configuration = new ClientConfiguration();

// Maximum concurrent requests. Default: 5.
// configuration.setMaxConcurrentRequest(3);

// Socket-layer data transmission timeout in milliseconds. Default: 60000.
// configuration.setSocketTimeout(50000);

// Connection establishment timeout in milliseconds. Default: 60000.
// configuration.setConnectionTimeout(50000);

// Maximum log file size. Default: 5 MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);

// Maximum retries after a request fails. Default: 2.
// configuration.setMaxErrorRetry(3);

// Skip CNAME resolution for specified endpoints.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);

// Proxy server settings.
// configuration.setProxyHost("<your-proxy-host>");
// configuration.setProxyPort(8080);

// Custom string appended to the User-Agent header.
// configuration.setUserAgentMark("<your-user-agent>");

// Enable CRC-64 verification. Default: false.
// configuration.setCheckCRC64(true);

// Follow HTTP redirects. Default: false.
// configuration.setFollowRedirectsEnable(true);

// Custom OkHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());

configuration.setSignVersion(SignVersion.V4);

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Enable logging

The mobile environment is complex and issues can be difficult to reproduce. Enable logging before using OSSClient to capture request data, response data, and exception details locally.

Call OSSLog.enableLog() before initializing OSSClient:

// Enable logging. Logs are viewable in the console.
// Log files are also written to \OSSLog\logs.csv on the device's built-in SD card (disabled by default).
OSSLog.enableLog();

Each log entry captures:

  • Android version and device model

  • Network state and connection type

  • Request and response details (request ID, response headers)

  • Exception information

Sample log entry:

android_version: 5.1
mobile_model: XT1085
network_state: connected
network_type: WIFI
[2017-09-05 16:54:52] - Encounter local exception: //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

To store logs off-device, upload the log files to your own server or use Alibaba Cloud Simple Log Service.

Synchronous and asynchronous interfaces

The Android SDK provides both synchronous and asynchronous interfaces. Because Android prohibits network calls on the UI thread, use asynchronous interfaces for all network operations in production code.

Synchronous interfaces

A synchronous call blocks the calling thread until the operation completes. Never call synchronous interfaces on the UI thread.

When an error occurs, the SDK throws one of the following exceptions:

  • ClientException — a local error, such as a network connectivity issue or an invalid parameter

  • ServiceException — an error returned by OSS, such as an authentication failure or a server error

Asynchronous interfaces

An asynchronous call returns an OSSAsyncTask immediately. Pass a callback to handle the result or any exceptions.

OSSAsyncTask task = oss.asyncGetObject(...);
task.cancel();             // Cancel the task
task.waitUntilFinished();  // Block until the task completes
GetObjectResult result = task.getResult(); // Block and get the result

For upload and download interfaces, both synchronous and asynchronous examples are provided. For all other interfaces, asynchronous examples are the primary examples.

What's next