Use the OSS Android SDK to create buckets, upload objects, and download objects.
Prerequisites
The Android SDK is installed. Installation (Android SDK).
Sample project
The OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET fields in the sample project's Config class are for local debugging and feature verification only. Never hardcode a long-term AccessKey pair in a production mobile app. In production, use one of the following approaches:
-
Client-side direct transfer: the mobile app fetches an STS temporary credential from your application server and uses it to initialize an OSSClient. For setup instructions, see Set up direct data transfer for mobile apps.
-
Server-generated presigned URLs: your application server generates presigned URLs and hands them to the mobile app, which uploads or downloads over standard HTTP and never holds a credential. Recommended for privacy-sensitive data such as ID cards, facial images, and payment credentials. For details, see Authorize access (Android SDK).
To use the sample project:
-
View the sample directory for examples of uploading local files, downloading objects, resumable uploads, and callbacks.
-
Clone the project using Git.
Before you run this project, configure the parameters in the Config file:
public class Config {
// In this example, the endpoint for the China (Hangzhou) region is used. Specify the endpoint for your region.
public static final String OSS_ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the callback URL.
public static final String OSS_CALLBACK_URL = "https://oss-demo.aliyuncs.com:23450";
// Specify the URL of the STS authentication server.
// You can also start a local STS authentication server based on the script in the project's sts_local_server directory.
public static final String STS_SERVER_URL = "http://****/sts/getsts";
public static final String BUCKET_NAME = "yourBucketName";
public static final String OSS_ACCESS_KEY_ID = "yourAccessKeyId";;
public static final String OSS_ACCESS_KEY_SECRET = "yourAccessKeySecret";
public static final int DOWNLOAD_SUC = 1;
public static final int DOWNLOAD_Fail = 2;
public static final int UPLOAD_SUC = 3;
public static final int UPLOAD_Fail = 4;
public static final int UPLOAD_PROGRESS = 5;
public static final int LIST_SUC = 6;
public static final int HEAD_SUC = 7;
public static final int RESUMABLE_SUC = 8;
public static final int SIGN_SUC = 9;
public static final int BUCKET_SUC = 10;
public static final int GET_STS_SUC = 11;
public static final int MULTIPART_SUC = 12;
public static final int STS_TOKEN_SUC = 13;
public static final int FAIL = 9999;
public static final int REQUESTCODE_AUTH = 10111;
public static final int REQUESTCODE_LOCALPHOTOS = 10112;
}
-
To configure the STS authentication server URL, follow Quickly build a mobile app direct upload service.
-
The sts_local_server script is available on GitHub.
-
To create an AccessKey pair, see Create an AccessKey pair.
Create a bucket
A bucket is a globally unique namespace in OSS that stores any number of objects.
// 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";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
String region = "yourRegion";
// The temporary AccessKey pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";
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);
// Specify the bucket name.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("bucketName");
// Set the access control list (ACL) of the bucket to public read. The default ACL is private.
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
// Specify the region where the bucket is located.
createBucketRequest.setLocationConstraint("oss-cn-hangzhou");
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
@Override
public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
Log.d("locationConstraint", request.getLocationConstraint());
}
@Override
public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
// The request failed.
if (clientException != null) {
// Client exception, such as a network error.
clientException.printStackTrace();
}
if (serviceException != null) {
// Service exception.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
Upload an object
Upload a local file to OSS as an object:
// 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";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
String region = "yourRegion";
// The temporary AccessKey pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";
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 upload request.
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");
// You can set a progress callback for asynchronous uploads.
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
}
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
Log.d("ETag", result.getETag());
Log.d("RequestId", result.getRequestId());
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// The request failed.
if (clientExcepion != null) {
// Client exception, such as a network error.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Service exception.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// task.cancel(); // You can cancel the task.
// task.waitUntilFinished(); // Wait until the upload is complete.
Download an object
Download an object from OSS to a local file:
// 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 pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set 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 a download request.
GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectName>");
OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// The request was successful.
Log.d("asyncGetObject", "DownloadSuccess");
Log.d("Content-Length", "" + result.getContentLength());
InputStream inputStream = result.getObjectContent();
byte[] buffer = new byte[2048];
int len;
try {
while ((len = inputStream.read(buffer)) != -1) {
// Add your code here to process the downloaded data.
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// The request failed.
if (clientExcepion != null) {
// Client exception, such as a network error.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Service exception.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// Cancel the task.
// task.cancel();
// Wait for the task to complete.
// task.waitUntilFinished();