This topic describes how to use OSS Android SDK to quickly perform common OSS operations, such as creating a bucket, uploading an object, and downloading an object.

You can use the sample project in the following two methods:

  • View the sample directory which includes sample projects of uploading local file, downloading objects, resumable upload, and setting callback. For more information, see Github.
  • Run the git clone command to clone the project.
Before running the project, you must configure the Config parameter. The sample code of configuring this parameter is as follows:
public class Config {

    // To run the sample correctly, the following variables must have valid values.
    // The endpoint value below is just the example. Please use proper value according to your region

    // Specify the endpoint that you want to access.
    public static final String OSS_ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com";
    // Specify the URL used to test the callback function.
    public static final String OSS_CALLBACK_URL = "http://oss-demo.aliyuncs.com:23450";
    // Specify the address of the 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";//Specify the URL of the STS authentication server.

    public static final String BUCKET_NAME = "Input the bucket name.";
    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;
}
Note

Create a bucket

A bucket is a container for objects stored in OSS. Every object is contained in a bucket.

Run the following code to create a bucket:

CreateBucketRequest createBucketRequest = new CreateBucketRequest("<bucketName>");
// Set the ACL for the bucket to public-read. The default ACL for a created bucket is private.
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead); 
// Specify the region where the bucket belongs to.
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 the exceptions returned for the request.
        if (clientException != null) {
            // A local exception (such as network exception) occurs.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurs.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

For the naming conventions for a bucket, see Basic concepts. For more information about how to create a bucket, see Manage buckets.

For more information about the endpoints, see Regions and endpoints.

Upload an object

Run the following code to upload a specified local file to OSS:

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

// You can configure the callback function when calling the asynchorous interface to upload a file.
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 the exceptions returned for the request.
        if (clientExcepion != null) {
            // A local exception (such as network exception) occurs.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurs.
            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 upload task.
// task.waitUntilFinished(); // You can also wait until the task is complete.

Download a specified object

Run the following code to download a specified object to the local device.

// Construct 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 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 which includes an instance of the input stream is returned. Add your own code to process the input stream.
    public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Hanlde exceptions returned to the request.
        if (clientExcepion != null) {
            // A local exception (such as network exception) occurs.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurs.
            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(); // You can also wait untile the task is complete.
Note You must process the returned input stream by running your own code.