tencent cloud

Cloud Object Storage

Downloading Objects

Download
Modo Foco
Tamanho da Fonte
Última atualização: 2026-05-15 14:59:09

Introduction

This document provides example code and descriptions for downloading objects from COS using the Android SDK. The content is divided into two parts: the advanced API and the simple API.

Must-Knows

If you use simple download, you must have read permission for the target object. When you configure an authorization policy, the action must be set to cos:GetObject. For more authorization information, see CAM-supported business APIs.
If you use advanced download, which supports resumable transfer, a HEAD request is sent before the download to obtain file information. Therefore, you must have head and read permissions for the target object. When you configure an authorization policy, the action must be set to cos:GetObject and cos:HeadObject. For more authorization information, see CAM-supported business APIs.

Related Examples

Feature Name
Description
Example code
Advanced API
The advanced interface supports pausing, resuming, and canceling download requests, and also supports the resumable download feature.
Simple API
The GET Object API can download objects to local files but does not support the resumable download feature.

Advanced API (recommended)

The advanced API supports pausing, resuming, and canceling download requests, and also supports the resumable download feature.

Prerequisites: Creating a TransferManager

Before using the advanced API, you must first create a TransferManager instance. Before creating a TransferManager instance, you need to create a CosXmlService instance. For detailed code, see Creating CosXmlService.
// Initialize TransferConfig. The default configuration is used here. If you need to customize it, see the SDK API documentation.
// By default, files larger than or equal to 2 MB are automatically uploaded in parts, with a part size of -1 MB. You can modify the part size threshold using the following code.
TransferConfig transferConfig = new TransferConfig.Builder() // Set the minimum object size to enable multipart upload. The default is 2 MB. .setDivisionForUpload(2097152) // Set the part size for multipart upload. The default is 1 MB. .setSliceSizeForUpload(1048576) // Set whether to force simple upload and disable multipart upload. .setForceSimpleUpload(false) .build();
// Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

Use Case: Downloading an Object

// A bucket name consists of bucketname-appid. The appid must be included. You can view bucket names in the COS console. https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key.
// Local directory path
String savePathDir = context.getExternalCacheDir().toString();
// The file name saved locally. If left blank (null), it will be the same as the file name on COS.
String savedFileName = "exampleobject.txt";

Context applicationContext = context.getApplicationContext(); // application
// context
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext,
bucket, cosPath, savePathDir, savedFileName);

// Set the download progress callback
cosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long complete, long target) {
// todo Do something to update progress...
}
});
// Set the result callback
cosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLDownloadTask.COSXMLDownloadTaskResult downloadTaskResult =
(COSXMLDownloadTask.COSXMLDownloadTaskResult) result;
}

// If you call the API using kotlin, note that the exception in the callback method must be nullable. Otherwise, the onFail method will not be called, as follows:
// The type of clientException is CosXmlClientException?, and the type of serviceException is CosXmlServiceException?
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else {
serviceException.printStackTrace();
}
}
});
// Set the task status callback to view the task progress.
cosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {
@Override
public void onStateChanged(TransferState state) {
// todo notify transfer state
}
});

Use Case: Pausing, Resuming, and Canceling a Download

To pause a download task, you can use the following methods:
cosxmlDownloadTask.pause();
After pausing, you can resume the download using the following methods:
cosxmlDownloadTask.resume();
You can also cancel the download using the following methods:
cosxmlDownloadTask.cancel();

Use Case: Configuring Download Resumption

// TransferManager supports resumable downloads. You only need to ensure that the bucket, cosPath, savePathDir, and savedFileName
// If the parameters remain the same, the SDK will resume the download from the last position.
// A bucket name consists of bucketname-appid. The appid must be included. You can view bucket names in the COS console. https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key.
// Local directory path
String savePathDir = context.getExternalCacheDir().toString();
// The file name saved locally. If left blank (null), it will be the same as the file name on COS.
String savedFileName = "exampleobject.txt";

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, cosPath, savePathDir, savedFileName);

Context applicationContext = context.getApplicationContext(); // application
// context
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext, getObjectRequest);

Use Case: Downloading in Batches

// The location identifier of the object in the bucket, also known as the object key.
String[] cosPaths = new String[] {
"exampleobject1.txt",
"exampleobject2.txt",
"exampleobject3.txt",
};

for (String cosPath : cosPaths) {
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext,
bucket, cosPath, savePathDir, savedFileName);
// Set the result callback.
cosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {
COSXMLDownloadTask.COSXMLDownloadTaskResult downloadResult =
(COSXMLDownloadTask.COSXMLDownloadTaskResult) result;
}

// If you call the API using kotlin, note that the exception in the callback method must be nullable. Otherwise, the onFail method will not be called, as follows:
// The type of clientException is CosXmlClientException?, and the type of serviceException is CosXmlServiceException?
@Override
public void onFail(CosXmlRequest request,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else {
serviceException.printStackTrace();
}
}
});
}

Use Case: Downloading a Directory

boolean isTruncated = true;
String marker = null;
try {
while (isTruncated) {
GetBucketRequest getBucketRequest = new GetBucketRequest(region, bucket, directoryPath);
// Set pagination information.
getBucketRequest.setMarker(marker);
// Do not query subdirectories.
getBucketRequest.setDelimiter("/");
GetBucketResult getBucketResult = cosXmlService.getBucket(getBucketRequest);
// Batch download.
for (ListBucket.Contents content : getBucketResult.listBucket.contentsList) {
GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, content.key, savePathDir);
transferManager.download(context,getObjectRequest);
}
isTruncated = getBucketResult.listBucket.isTruncated;
marker = getBucketResult.listBucket.nextMarker;
}
} catch (CosXmlServiceException serviceException) {
serviceException.printStackTrace();
} catch (CosXmlClientException clientException) {
clientException.printStackTrace();
}

Use Case: Anonymous Download (Downloading Public Files Without Providing a Secret Key)

// Initialize TransferConfig. The default configuration is used here. If you need to customize it, see the SDK API documentation.
TransferConfig transferConfig = new TransferConfig.Builder().build();
// Initialize TransferManager
CosXmlServiceConfig cosXmlServiceConfig = new CosXmlServiceConfig.Builder()
.setRegion("ap-guangzhou")
.builder();
// When generating a CosXmlService for anonymous download, you do not need to provide a key generator.
CosXmlService cosXmlService = new CosXmlService(context, cosXmlServiceConfig);
TransferManager transferManager = new TransferManager(cosXmlService, transferConfig);
// A bucket name consists of bucketname-appid. The appid must be included. You can view bucket names in the COS console. https://console.tencentcloud.com/cos5/bucket
String bucket = "examplebucket-1250000000";
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key.
// Local directory path
String savePathDir = context.getExternalCacheDir().toString();
// The file name saved locally. If left blank (null), it will be the same as the file name on COS.
String savedFileName = "exampleobject.txt";

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, cosPath, savePathDir, savedFileName);

Context applicationContext = context.getApplicationContext(); // application
// context
COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(applicationContext, getObjectRequest);

Simple Download

Download an object (file/object) to the local computer (GET Object).

Prerequisites: Creating a CosXmlService

Before a COS API is called, you must first create a CosXmlService instance. For detailed code, see Creating CosXmlService.

Use Case: Downloading an Object to a Local File

String bucket = "examplebucket-1250000000"; // Bucket name. Format: BucketName-APPID
String cosPath = "exampleobject.txt"; // The location identifier of the object in the bucket, also known as the object key.
String savePath = context.getExternalCacheDir().toString(); // Local path

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, cosPath,
savePath);
getObjectRequest.setProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long progress, long max) {
// todo Do something to update progress...
}
});

cosXmlService.getObjectAsync(getObjectRequest, new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest cosXmlRequest,
CosXmlResult cosXmlResult) {
GetObjectResult getObjectResult = (GetObjectResult) cosXmlResult;
}

// If you call the API using kotlin, note that the exception in the callback method must be nullable. Otherwise, the onFail method will not be called, as follows:
// The type of clientException is CosXmlClientException?, and the type of serviceException is CosXmlServiceException?
@Override
public void onFail(CosXmlRequest cosXmlRequest,
@Nullable CosXmlClientException clientException,
@Nullable CosXmlServiceException serviceException) {
if (clientException != null) {
clientException.printStackTrace();
} else {
serviceException.printStackTrace();
}
}
});

SDK API Reference

For detailed parameters and method descriptions of all SDK interfaces, see SDK API Reference.

API Operations

For the description of the APIs related to the download object interface, see GET Object and HEAD Object.

Ajuda e Suporte

Esta página foi útil?

comentários