All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK for Android

Last Updated:Jan 12, 2024

This topic describes how to use Object Storage Service (OSS) SDK for Android to perform routine operations such as creating a bucket, uploading an object, and downloading an object.

Prerequisites

OSS SDK for Android is installed. For more information, see Installation.

Sample project

You can use the following methods to try the sample project:

  • View the sample directory which includes code examples for uploading local files, downloading objects, performing resumable upload, and configuring callbacks. For more information, visit GitHub.

  • Run the git clone command to clone the project.

Before running the project, you must configure the Config class. The following sample code provides an example on how to configure the Config class:

public class Config {    

    // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
    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 Security Token Service (STS) authentication server. 
    // You can also start the local STS authentication server by running the local authentication script in the sts_local_server directory of the project. 
    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;
}

Create a bucket

A bucket is a global namespace in OSS. A bucket is a container that is used to store objects. The following sample code provides an example on how to create a bucket:

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

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

// Specify the name of the bucket. 
CreateBucketRequest createBucketRequest = new CreateBucketRequest("bucketName");
// Set the access control list (ACL) of the bucket to public-read. The default bucket ACL is private. 
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
// Specify the region in which 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) {
        // Handle request exceptions. 
        if (clientException != null) {
            // Handle client exceptions, such as network exceptions. 
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Handle service exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Upload an object.

The following sample code provides an example on how to upload a local file to OSS:

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

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

// Construct a file upload request. 
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");

// When you upload the local file in asynchronous mode, you can configure the progress callback. 
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) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client exceptions, such as network exceptions. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle service exceptions. 
            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 download task. 
// task.waitUntilFinished(); // Wait until the upload is complete.

Download an object

The following sample code provides an example on how to download an object to a local device:

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

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
// Create an OSSClient instance. 
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
// Construct a request to download the object. 
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 is 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) {
                // You can add your own code here to process the downloaded data. 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    // If the GetObject request is successful, GetObjectResult is returned. GetObjectResult includes an instance of the input stream. You need to handle the returned input stream. 
    public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client exceptions, such as network exceptions. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle service exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// Cancel the download task. 
// task.cancel(); 
// Wait until the object is downloaded. 
// task.waitUntilFinished();