tencent cloud

Cloud Object Storage

Getting Started

Unduh
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-06-30 09:31:40

Relevant Resources

COS (Cloud Object Storage) download link for the XML Java SDK: XML Java SDK.
Quick download link for the SDK: XML Java SDK.
Example Demo download address: COS XML Java SDK example.
For the SDK changelog, see Changelog.
For SDK FAQs, see: Java SDK FAQ.
Note:
To avoid unnecessary troubleshooting of cumbersome code and program localization issues, if you are new to COS or have a small amount of data, we recommend using more user-friendly, graphical interfaces such as the Console and COSBrowser, or the command-line tool COSCLI for batch operations.
If you encounter errors such as functions or methods not found when using the XML version SDK, please first upgrade the XML version SDK to the latest version and then retry.

Environment Configuration and Preparation

Environment Configuration

The SDK supports JDK 1.8 and later versions. You can check the Java version by running the command java -version.
For JDK installation methods, see Java Installation and Configuration.
Note:
For the meanings and acquisition methods of names, such as SecretId, SecretKey, and Bucket mentioned in this document, see COS Terminology Information.
Common classes in the COS Java SDK are located in the following packages:
Client configuration-related classes are located in the com.qcloud.cos.* package.
Authorization-related classes are located in the com.qcloud.cos.auth.* subpackage.
Exception-related classes are located in the com.qcloud.cos.exception.* subpackage.
Request-related classes are located in the com.qcloud.cos.model.* subpackage.
Region-related classes are located in the com.qcloud.cos.region.* subpackage.
Advanced API interfaces are located in the com.qcloud.cos.transfer.* subpackage.

Preparing the Environment

Before diving into writing your first line of code for production use, take two minutes to perform the following test. This ensures that your requests can reach the COS service and helps you confirm whether you've encountered issues that the majority of users face when using the Java SDK.
The following test assumes that you are attempting to access the COS service in the Guangzhou region.
Use the ping Test
Using curl Test
[root@VM_centos /data/home/]# ping cos.ap-guangzhou.myqcloud.com
PING cos.ap-guangzhou.myqcloud.com (9.*.*.*) xx(xx) bytes of data.
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=1 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=2 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=3 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=4 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=5 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=6 ttl=xx time=0.xxx ms
64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=7 ttl=xx time=0.xxx ms
^C
--- cos.ap-guangzhou.myqcloud.com ping statistics ---
x packets transmitted, x received, 0% packet loss, time xxxms
rtt min/avg/max/mdev = 0.xxx/0.xxx/0.xxx/0.xxx ms
If the result is similar to the above, the basic network connectivity and name service are normal. If other abnormal results are returned, prioritize troubleshooting environmental network issues or contact your local network administrator. After confirming everything is normal, proceed to the next step.
If you are on Windows, you can also click Start (or press the shortcut key: Win+R) > Run (enter cmd) > OK (or press Enter), then input the command ping cos.ap-guangzhou.myqcloud.com and press Enter to perform the test.
If using HTTP to access:
[root@VM_centos /data/home/]# curl http://cos.ap-guangzhou.myqcloud.com -v
* About to connect() to cos.ap-guangzhou.myqcloud.com port 80 (#0)
* Trying 9.*.*.*...
* Connected to cos.ap-guangzhou.myqcloud.com (9.*.*.*) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/*.*.0
> Host: cos.ap-guangzhou.myqcloud.com
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Content-Type: application/xml
< Content-Length: XXX
< Connection: keep-alive
< Date: XXX XXX GMT
< Server: tencent-cos
< x-cos-request-id: NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****
<
<?xml version='1.0' encoding='utf-8' ?>
<Error>
<Code>AccessDenied</Code>
<Message>Check auth failure because signture empty.</Message>
<ServerTime>XXX XXX</ServerTime>
<Resource>cos.ap-guangzhou.myqcloud.com/</Resource>
<RequestId>NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****==</RequestId>
</Error>

* Connection #0 to host cos.ap-guangzhou.myqcloud.com left intact
If using HTTPS to access:
[root@VM_centos /data/home/]# curl https://cos.ap-guangzhou.myqcloud.com -vk
* About to connect() to cos.ap-guangzhou.myqcloud.com port 443 (#0)
* Trying 9.*.*.*...
* Connected to cos.ap-guangzhou.myqcloud.com (9.*.*.*) port 443 (#0)
* Initializing NSS with certpath: XXXX
* skipping SSL peer certificate verification
* SSL connection using ******
* Server certificate:
* subject: CN=*.*.*.
* start date: XXX XXX GMT
* expire date: XXX XXX GMT
* common name: *.cos.ap-guangzhou.myqcloud.com
* issuer: XXX
> GET / HTTP/1.1
> User-Agent: curl/*.*.0
> Host: cos.ap-guangzhou.myqcloud.com
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Content-Type: application/xml
< Content-Length: XXX
< Connection: keep-alive
< Date: XXX XXX GMT
< Server: tencent-cos
< x-cos-request-id: NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****
<
<?xml version='1.0' encoding='utf-8' ?>
<Error>
<Code>AccessDenied</Code>
<Message>Check auth failure because signture empty.</Message>
<ServerTime>XXX XXX</ServerTime>
<Resource>cos.ap-guangzhou.myqcloud.com/</Resource>
<RequestId>NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****</RequestId>
</Error>

* Connection #0 to host cos.ap-guangzhou.myqcloud.com left intact
If the result is similar to the above, then the port connection is normal. If other abnormal results are returned, prioritize troubleshooting environmental network issues or contact your local network administrator. After confirming everything is normal, proceed to the next step.
In the Windows environment, some versions may require additional installation of the curl tool to perform tests.

Installing the SDK

Users can install the Java SDK via Maven or source code. The SDK can be uninstalled by removing the pom dependency or source code.

Method 1: Maven Installation

Add the relevant dependencies in the pom.xml file of the Maven project as follows:
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.227</version>
</dependency>
Note:
The dependency coordinates may not be the latest version; please click here to obtain the latest version.

Method 2: Source Code Installation

Download the source code from GitHub XML Java SDK or quick download address, and import via Maven. For example, in Eclipse, sequentially choose File > Import > maven > Existing Maven Projects.

Initialize COS Service

The following describes how to use the COS Java SDK to perform basic operations, such as initializing a client, creating a bucket, listing buckets, uploading objects, listing objects, downloading objects, and deleting objects. For classes used in the examples, you can click on them in the IDE to view all field and function definitions, which include detailed comments.

Import class name

The package name of the COS Java SDK is com.qcloud.cos.*. You can use IDEs such as Eclipse or IntelliJ to import the classes required for program execution.

Initialize the client

Before any requests related to COS services are performed, you need to instantiate an instance of the COSClient class, which is the object used to invoke COS APIs.
Note:
COSClient is a thread-safe class that allows multiple threads to access the same instance. Since the instance internally maintains a connection pool, creating multiple instances may exhaust program resources. Ensure only a single instance exists throughout the program's lifecycle. When the instance is no longer needed, call the shutdown method to disable it. If a new instance is required, first disable the previous instance.
It is recommended that users use temporary keys to call the SDK, thereby enhancing the security of SDK usage through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of resources beyond the target bucket or objects.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
Temporary Key Initialization (Recommended)
Permanent Key Initialization (Not Recommended)
If you use temporary keys to initialize COSClient (recommended), refer to Temporary Key Generation and Usage Guidelines for details. An example is shown below:
// 1 Pass the obtained temporary credentials (tmpSecretId, tmpSecretKey, sessionToken)
String tmpSecretId = "SECRETID";
String tmpSecretKey = "SECRETKEY";
String sessionToken = "TOKEN";
BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
// 2 Configure the bucket region
// The clientConfig includes set methods for configuring the region, https (defaulting to http), timeout, proxy, etc. For usage, refer to the source code or the Java SDK section in the FAQs.
Region region = new Region("COS_REGION"); //COS_REGION parameter: Configure it to the actual region of the bucket, such as ap-beijing. For more COS region abbreviations, see https://www.tencentcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(region);
// 3 Generating a COS client
COSClient cosClient = new COSClient(cred, clientConfig);
You can also use permanent keys to initialize COSClient (not recommended due to the risk of primary key leakage; avoid using in production environments). First, obtain the APPId, SecretId, and SecretKey on the API Key Management page in the CAM console. Refer to the following example:
// 1 Initialize user identity information (secretId, secretKey).
// To view and manage SECRETID and SECRETKEY, log in to the CAM console at https://console.tencentcloud.com/cam/capi
String secretId = System.getenv("secretId");//User's SecretId. It is recommended to use sub-account keys and follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretKey = System.getenv("secretKey");//User's SecretKey. It is recommended to use sub-account keys, follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 Set the bucket region. For COS region abbreviations, see https://www.tencentcloud.com/document/product/436/6224
// The clientConfig includes set methods for configuring region, https (defaulting to http), timeout, proxy, etc. For usage, refer to the source code or the Java SDK section in the FAQs.
Region region = new Region("COS_REGION");
ClientConfig clientConfig = new ClientConfig(region);
// It is recommended to configure the use of the https protocol here.
// Starting from version 5.6.54, https is used by default
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 Generating a cos client
COSClient cosClient = new COSClient(cred, clientConfig);
The ClientConfig class is a configuration information class, and its main members are as follows:
Member Name
Setting Method
Description
Type
region
Constructor or set method
The region where the bucket is located. For the COS region abbreviation, see the Regions and Access Domains document.
Region
httpProtocol
set method
The protocol used for requests; HTTPS is used by default to communicate with COS.
HttpProtocol
signExpired
set method
The validity period of the request signature: in seconds, defaults to 3600s.
long
connectionTimeout
set method
The timeout period for connecting to the COS service, unit: milliseconds, defaults to 30000ms.
int
socketTimeout
set method
The timeout period for the client to read data, unit: milliseconds, defaults to 30000ms.
int
httpProxyIp
set method
Proxy Server IP
String
httpProxyPort
set method
Port of the Proxy Server
int

Access COS Service

Create a bucket
Querying the Bucket List
PUT Object
Querying the Object List
Downloading an Object
Deleting Objects
After the region and bucket name are determined, refer to the following example to create a bucket. For complete bucket creation examples, visit GitHub.

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;
import com.qcloud.cos.region.Region;

public class BucketDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String cosRegion = System.getenv("REGION");
private static COSClient cosClient = createCli();

public static void main(String[] args) {
try {
createBucketDemo();
//createMAZBucketDemo();
} catch (Exception e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}

private static COSClient createCli() {
// 1 Initializing user identity information (appid, secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(cosRegion));
// 3 Generating a COS client
COSClient cosclient = new COSClient(cred, clientConfig);

return cosclient;
}

// Create bucket
private static void createBucketDemo() {
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
// Set the bucket permission to PublicRead (public read, private write). Other options include private read-write, public read, private write.
createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
Bucket bucket = cosClient.createBucket(createBucketRequest);
System.out.println("create bucket, bucketName is " + bucket.getName());
}

// Create Multi-AZ bucket
private static void createMAZBucketDemo() {
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);

try {
Bucket bucket = cosClient.createMAZBucket(createBucketRequest);
System.out.println("create MAZ bucket, bucketName is " + bucket.getName());
} catch (CosServiceException cse) {
cse.printStackTrace();
} catch (CosClientException cce) {
cce.printStackTrace();
}
}
}
Query the user's bucket list by referring to the following example. For complete examples of listing buckets, visit GitHub.

import java.util.ArrayList;
import java.util.List;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.ListBucketsRequest;
import com.qcloud.cos.model.ListBucketsResult;
import com.qcloud.cos.region.Region;

public class BucketDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String cosRegion = System.getenv("REGION");
private static COSClient cosClient = createCli();

public static void main(String[] args) {
try {
listBuckets();
} catch (Exception e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}

private static COSClient createCli() {
// 1 Initializing user identity information (appid, secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(cosRegion));
// 3 Generating a COS client
COSClient cosclient = new COSClient(cred, clientConfig);

return cosclient;
}

private static void listBuckets() {
List<Bucket> buckets = cosClient.listBuckets();

for (Bucket bucket : buckets) {
System.out.println(bucket.getName());
System.out.println(bucket.getLocation());
System.out.println(bucket.getOwner());
System.out.println(bucket.getType());
System.out.println(bucket.getBucketType());
}
}
}
For complete examples of uploading objects, please visit GitHub to view them.
Upload local files or input streams of known length to COS. It is suitable for small image files less than 20 MB. It supports files up to 5 GB. For files greater than 5 GB, use multipart upload or advanced APIs.
Note:
Advanced API interfaces are in the com.qcloud.cos.transfer.\\* subpackage.
If most of your local files exceed 20M, it is recommended that you use advanced APIs for uploading.
If an object with the same key already exists on COS, the uploaded object will overwrite the old object.
To create a directory object, see How do I create a directory in the SDK.
An object key is a unique identifier for an object in a bucket. For example, in the object access domain examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/images/picture.jpg, the object key is images/picture.jpg. For details, see instructions in object key.
Upload a file that does not exceed 5 GB, and the reference example is as follows:

import java.io.File;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

public class PutObjectDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String region = System.getenv("REGION");
private static COSClient cosClient = createCli();

public static void main(String[] args) {
try {
putLocalFileDemo();
} catch (Exception e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}

private static COSClient createCli() {
// Initialize user identity information (secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
// Generate a cos client
return new COSClient(cred, clientConfig);
}

private static void putLocalFileDemo() {
String key = "abc/abc.txt";
String localPath = "abc.txt";

PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));
try {
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
System.out.println(putObjectResult.getRequestId());
} catch (CosServiceException cse) {
cse.printStackTrace();
} catch (CosClientException cce) {
cce.printStackTrace();
}
}
}
List objects in a bucket by referring to the following example. For a complete example of listing objects, visit GitHub to view.

import java.util.List;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.COSVersionSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ListVersionsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.model.VersionListing;
import com.qcloud.cos.region.Region;

public class ListObjectsDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String region = System.getenv("REGION");
private static COSClient cosClient = createClient();

public static void main(String[] args) {
try {
listObjectsVersions();
//listObjectsDemo();
//listAllObjects();
} catch (Exception e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}

private static COSClient createClient() {
// Initialize user identity information (secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
// Generate a cos client
COSClient cosclient = new COSClient(cred, clientConfig);

return cosclient;
}

private static void listObjectsDemo() {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// Setting the bucket name
listObjectsRequest.setBucketName(bucketName);
// prefix means the key of the listed object starts with prefix.
listObjectsRequest.setPrefix("");
// Setting the maximum number of objects to be traversed, with a maximum number of 1000 objects supported by a listobject
listObjectsRequest.setMaxKeys(1000);
// listObjectsRequest.setDelimiter("/");
ObjectListing objectListing = null;
try {
objectListing = cosClient.listObjects(listObjectsRequest);
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}
// common prefix indicates the path truncated by delimiter. If delimiter is set to /, common prefix indicates the path of all subdirectories.
List<String> commonPrefixs = objectListing.getCommonPrefixes();

// object summary represents a list of all listed objects.
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
// File path key
String key = cosObjectSummary.getKey();
// File etag
String etag = cosObjectSummary.getETag();
// Length of the file
long fileSize = cosObjectSummary.getSize();
// File storage type
String storageClasses = cosObjectSummary.getStorageClass();

System.out.println("key: " + key);
}
}

// To obtain more than the maxkey number of objects or retrieve all objects, you need to loop through listobject calls, using the next marker returned from the previous call as the marker for the next call.
// Until the returned truncated is false
private static void listAllObjects() {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// Setting the bucket name
listObjectsRequest.setBucketName(bucketName);
// prefix means the key of the listed object starts with prefix.
listObjectsRequest.setPrefix("");
// deliter represents the delimiter. If it is set to /, it means listing the objects in the current directory. If it is set to null, it means listing all objects.
listObjectsRequest.setDelimiter("");
// Setting the maximum number of objects to be traversed, with a maximum number of 1000 objects supported by a listobject
listObjectsRequest.setMaxKeys(1000);
ObjectListing objectListing = null;
do {

try {
objectListing = cosClient.listObjects(listObjectsRequest);
} catch (CosServiceException e) {
e.printStackTrace();
return;
} catch (CosClientException e) {
e.printStackTrace();
return;
}
// common prefix indicates the path truncated by delimiter. If delimiter is set to /, common prefix indicates the path of all subdirectories.
List<String> commonPrefixs = objectListing.getCommonPrefixes();

// object summary represents a list of all listed objects.
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
// File path key
String key = cosObjectSummary.getKey();
// File etag
String etag = cosObjectSummary.getETag();
// Length of the file
long fileSize = cosObjectSummary.getSize();
// File storage type
String storageClasses = cosObjectSummary.getStorageClass();
}

String nextMarker = objectListing.getNextMarker();
listObjectsRequest.setMarker(nextMarker);
} while (objectListing.isTruncated());
}

private static void listObjectsVersions() {
ListVersionsRequest listVersionsRequest = new ListVersionsRequest();
listVersionsRequest.setBucketName(bucketName);
listVersionsRequest.setPrefix("");

VersionListing versionListing = null;

do {
try {
versionListing = cosClient.listVersions(listVersionsRequest);
} catch (CosServiceException e) {
e.printStackTrace();
return;
} catch (CosClientException e) {
e.printStackTrace();
return;
}

List<COSVersionSummary> cosVersionSummaries = versionListing.getVersionSummaries();
for (COSVersionSummary cosVersionSummary : cosVersionSummaries) {
System.out.println(cosVersionSummary.getKey() + ":" + cosVersionSummary.getVersionId());
}

String keyMarker = versionListing.getNextKeyMarker();
String versionIdMarker = versionListing.getNextVersionIdMarker();

listVersionsRequest.setKeyMarker(keyMarker);
listVersionsRequest.setVersionIdMarker(versionIdMarker);

} while (versionListing.isTruncated());
}
}
After uploading an object, you can use the same key to call the GetObject API to download the object locally. Alternatively, you can generate a presigned URL (set method to GET for download; see Presigned URL for details) and share it with other endpoints for downloading. However, if your file is set with private read permission, please note the validity period of the presigned URL.
Download the file to the specified local path. Refer to the following example. For complete examples of downloading objects, see GitHub.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;

public class GetObjectDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String region = System.getenv("REGION");
private static COSClient cosClient = createClient();

public static void main(String[] args) {
try {
getObjectToFileDemo();
//getObjectInputStreamDemo();
} catch (Exception e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
}

private static COSClient createClient() {
// Initialize user identity information (secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
// Generate a cos client
COSClient cosclient = new COSClient(cred, clientConfig);

return cosclient;
}

private static void getObjectToFileDemo() {
String key = "test/my_test.json";
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
// Set the single link speed limit for download (if needed); can be ignored if not required
getObjectRequest.setTrafficLimit(8*1024*1024);

try {
File localFile = new File("my_test.json");
ObjectMetadata objectMetadata = cosClient.getObject(getObjectRequest, localFile);
System.out.println(objectMetadata.getContentLength());
} catch (CosServiceException cse) {
cse.printStackTrace();
} catch (CosClientException cce) {
cce.printStackTrace();
}
}

private static void getObjectInputStreamDemo() throws IOException {
String key = "test/my_test.json";
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
InputStream cosObjectInput = null;

try {
COSObject cosObject = cosClient.getObject(getObjectRequest);
cosObjectInput = cosObject.getObjectContent();
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}

// Process the downloaded stream
// This is a direct read; adjust according to actual needs
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(cosObjectInput);
} catch (IOException e) {
e.printStackTrace();
} finally {
// Be sure to call close() after using the stream
cosObjectInput.close();
}
}
}
Note:
Once an object is deleted, its corresponding data can no longer be accessed.
Delete the object at the specified path in COS. Refer to the following sample code. For complete examples of deleting objects, see GitHub.

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.region.Region;

public class DelFileDemo {
private static String secretId = System.getenv("SECRETID");
private static String secretKey = System.getenv("SECRETKEY");
private static String bucketName = System.getenv("BUCKET_NAME");
private static String region = System.getenv("REGION");
private static COSClient cosClient = createCli();
public static void main(String[] args) {
delSingleFile();

if (cosClient != null) {
cosClient.shutdown();
}
}

private static COSClient createCli() {
// 1 Initializing user identity information (secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3 Generating a COS client
COSClient cosclient = new COSClient(cred, clientConfig);

return cosclient;
}

// Delete a single file (without version ID, i.e., the bucket does not have versioning enabled)
private static void delSingleFile() {
try {
String key = "aaa/bbb.txt";
cosClient.deleteObject(bucketName, key);
} catch (CosServiceException e) { // If there are other errors, such as parameter errors or failed authentication, a CosServiceException will be thrown.
e.printStackTrace();
} catch (CosClientException e) { // If there is a client error, such as failure to connect to COS
e.printStackTrace();
}

}
}

Default Request Retry Policy

Requests initiated by the cosClient generated by the SDK automatically retry upon encountering errors by default. The retry rules are as follows:
Number of retries: The default value is 3, which can be set via clientConfig.setMaxErrorRetry. If set to 0, no retries will be performed for any type of error request.
Error types for retry: All errors reporting IOException in client-side exceptions; errors with status codes 500, 502, 503, 504 in server-side exceptions.
The retry interval: increases according to the pattern of 200ms, 400ms, 800ms... based on the number of retries, with a maximum retry interval of 20s.
Users can also configure the retry policy based on their needs. The code is as follows:
Set the number of retries
Set the retry policy

Region region = new Region("COS_REGION");
ClientConfig clientConfig = new ClientConfig(region);
// Set the maximum number of retries to 4
clientConfig.setMaxErrorRetry = 4;

// Custom retry policy
public class OnlyIOExceptionRetryPolicy extends RetryPolicy {
@Override
public <X extends CosServiceRequest> boolean shouldRetry(CosHttpRequest<X> request,
HttpResponse response,
Exception exception,
int retryIndex) {
// If it is a client-side IOException, retry; otherwise, do not retry
if (exception.getCause() instanceof IOException) {
return true;
}
return false;
}
}

Region region = new Region("COS_REGION");
ClientConfig clientConfig = new ClientConfig(region);
RetryPolicy myRetryPolicy = new OnlyIOExceptionRetryPolicy();
// Set the custom retry policy
clientConfig.setRetryPolicy(myRetryPolicy);

FAQs

You may encounter some common issues during usage. For related solutions, see Java SDK FAQ.

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan