### Complete Authentication Setup Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/03-Authentication.md This example demonstrates the full process of setting up authentication and creating a COS client. It includes creating credentials, a credentials provider, client configuration, and the COS client itself. ```java import com.qcloud.cos.*; import com.qcloud.cos.auth.*; import com.qcloud.cos.region.Region; public class AuthenticationExample { public static void main(String[] args) { // 1. Create credentials String secretId = "your-secret-id"; String secretKey = "your-secret-key"; COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 2. Create credentials provider COSCredentialsProvider credProvider = new COSStaticCredentialsProvider(cred); // 3. Create client config ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing")); // 4. Create COS client COSClient cosClient = new COSClient(credProvider, clientConfig); // 5. Use the client try { cosClient.putObject("my-bucket-1234567890", "test.txt", "Hello COS!"); } finally { cosClient.shutdown(); } } } ``` -------------------------------- ### Example: Pagination with ListObjects Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/08-Types.md Demonstrates how to use ListObjectsRequest and ObjectListing to paginate through objects in a bucket. ```java ListObjectsRequest request = new ListObjectsRequest(); request.setBucketName(bucketName); request.setMaxKeys(100); ObjectListing listing = cosClient.listObjects(request); while (listing.isTruncated()) { request.setMarker(listing.getNextMarker()); listing = cosClient.listObjects(request); } ``` -------------------------------- ### Instantiate ClientConfig with a Region Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Example of creating a ClientConfig object and setting the region to 'ap-beijing'. ```java ClientConfig config = new ClientConfig(new Region("ap-beijing")); ``` -------------------------------- ### Basic Client Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Initializes a `ClientConfig` object with a specified region. This is the fundamental step for client setup. ```java Region region = new Region("ap-beijing"); ClientConfig config = new ClientConfig(region); ``` -------------------------------- ### Region Initialization and Usage Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Demonstrates how to create Region objects and use them with ClientConfig. Also shows how to list multiple regions. ```java Region region = new Region("ap-beijing"); ClientConfig config = new ClientConfig(region); // List all regions (if needed) List allRegions = Arrays.asList( new Region("ap-beijing"), new Region("ap-shanghai"), new Region("eu-frankfurt") ); ``` -------------------------------- ### PutObjectResult Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Demonstrates how to access information from the response of an object upload operation. ```java PutObjectResult result = cosClient.putObject(request); System.out.println("ETag: " + result.getETag()); System.out.println("Version ID: " + result.getVersionId()); System.out.println("CRC64: " + result.getCrc64()); ``` -------------------------------- ### Configure Connection Timeouts for ClientConfig Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Example demonstrating how to set connection, socket, and overall request timeouts for a ClientConfig. ```java ClientConfig config = new ClientConfig(new Region("ap-beijing")); config.setConnectionTimeout(30 * 1000); // 30 seconds config.setSocketTimeout(30 * 1000); // 30 seconds config.setRequestTimeout(5 * 60 * 1000); // 5 minutes ``` -------------------------------- ### Example: Completing a Multipart Upload Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/08-Types.md Shows how to create a list of PartETag objects and use them to complete a multipart upload request. ```java List partETags = new ArrayList<>(); partETags.add(new PartETag(1, "abc123...")); partETags.add(new PartETag(2, "def456...")); partETags.add(new PartETag(3, "ghi789...")); CompleteMultipartUploadRequest request = new CompleteMultipartUploadRequest( bucketName, key, uploadId); request.setPartETags(partETags); ``` -------------------------------- ### GetObjectRequest Example with Constraints Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Illustrates setting various constraints and options for a download request, such as byte range, ETag matching, and modification dates. ```java GetObjectRequest request = new GetObjectRequest(bucketName, key); request.setRange(0, 1023); // First 1KB // Only download if ETag matches request.setMatchingETagConstraints(Arrays.asList("abc123def456")); // Only download if modified since Date since = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); request.setModifiedSinceConstraint(since); COSObject obj = cosClient.getObject(request); ``` -------------------------------- ### Get User-Agent String Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the currently configured user-agent string for the SDK. ```java public String getUserAgent() ``` -------------------------------- ### PutObjectRequest Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Shows how to set various properties for an upload request, including metadata, storage class, and ACL. ```java PutObjectRequest request = new PutObjectRequest(bucketName, "path/to/object.txt", new File("/local/file.txt")); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("text/plain"); metadata.addUserMetadata("custom-key", "custom-value"); request.setObjectMetadata(metadata); request.setStorageClass("INTELLIGENT_TIERING"); request.setCannedAcl(CannedAccessControlList.PublicRead); PutObjectResult result = cosClient.putObject(request); ``` -------------------------------- ### Basic COS Client Initialization and Usage Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/00-README.md Demonstrates how to create credentials, configure the client, initialize COSClient, and perform basic object operations like put, get, and delete. Ensure to shut down the client when done. ```java // Create credentials COSCredentials cred = new BasicCOSCredentials("secretId", "secretKey"); // Configure client ClientConfig config = new ClientConfig(new Region("ap-beijing")); // Create client COSClient cosClient = new COSClient(cred, config); // Use the client try { cosClient.putObject(bucketName, key, file); COSObject obj = cosClient.getObject(bucketName, key); cosClient.deleteObject(bucketName, key); } finally { cosClient.shutdown(); } ``` -------------------------------- ### Create a Private Bucket Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Example of creating a new bucket with a specified name and setting its Access Control List (ACL) to private. ```java CreateBucketRequest request = new CreateBucketRequest("my-bucket-123456789"); request.setCannedAcl(CannedAccessControlList.Private); cosClient.createBucket(request); ``` -------------------------------- ### Initiate Multipart Upload Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Starts a multipart upload process for a given object key and bucket. It returns an upload ID that is essential for subsequent part uploads. ```java InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, key); InitiateMultipartUploadResult result = cosClient.initiateMultipartUpload(request); String uploadId = result.getUploadId(); ``` -------------------------------- ### Object Tagging Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Provides examples for retrieving and setting object tags using `GetObjectTaggingRequest` and `SetObjectTaggingRequest`. ```APIDOC ## Object Tagging ### GetObjectTaggingRequest Request to retrieve object tags. **Package:** `com.qcloud.cos.model` ```java GetObjectTaggingRequest request = new GetObjectTaggingRequest(bucketName, key); GetObjectTaggingResponse response = cosClient.getObjectTagging(request); Map tags = response.getTagSet().getTags(); for (Map.Entry entry : tags.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } ``` ### SetObjectTaggingRequest Request to set object tags. ```java TagSet tagSet = new TagSet(); tagSet.addTag("classification", "confidential"); tagSet.addTag("processed", "true"); SetObjectTaggingRequest request = new SetObjectTaggingRequest( bucketName, key, tagSet); cosClient.setObjectTagging(request); ``` ``` -------------------------------- ### Set Object and Bucket ACLs Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Examples demonstrating how to set ACLs for objects using `PutObjectRequest` and for buckets using `CreateBucketRequest` with `CannedAccessControlList`. ```java // For objects PutObjectRequest request = new PutObjectRequest(bucketName, key, file); request.setCannedAcl(CannedAccessControlList.PublicRead); cosClient.putObject(request); // For buckets CreateBucketRequest createRequest = new CreateBucketRequest(bucketName); createRequest.setCannedAcl(CannedAccessControlList.Private); cosClient.createBucket(createRequest); ``` -------------------------------- ### Lifecycle Configuration Methods Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Methods for managing bucket lifecycle rules, including getting, setting, and adding individual rules. ```APIDOC ## Lifecycle Configuration Methods ### `getRules()` #### Description Retrieves the list of lifecycle rules configured for the bucket. ### `setRules(List)` #### Description Sets all lifecycle rules for the bucket. This will replace any existing rules. ### `addRule(Rule)` #### Description Adds a single lifecycle rule to the bucket's configuration. ``` -------------------------------- ### Environment Variable Setup for Credentials Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/03-Authentication.md This bash snippet shows how to store your COS credentials in environment variables. The subsequent Java code demonstrates how to read these variables to create `COSCredentials`. ```bash # Store credentials in environment variables (not recommended for production) export COS_SECRET_ID="your-secret-id" export COS_SECRET_KEY="your-secret-key" ``` ```java String secretId = System.getenv("COS_SECRET_ID"); String secretKey = System.getenv("COS_SECRET_KEY"); COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); ``` -------------------------------- ### InstanceProfileCredentials Methods Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/03-Authentication.md Represents credentials fetched from an instance metadata service, providing methods to get access key, secret key, session token, and expiration time. ```java public String getAccessKeyId() ``` ```java public String getSecretAccessKey() ``` ```java public String getSessionToken() ``` ```java public Date getExpiration() ``` -------------------------------- ### Monitor Upload Progress Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Implement a listener to track upload progress, including transfer start, byte transfers, completion, failure, and cancellation events. ```java PutObjectRequest request = new PutObjectRequest(bucketName, key, file); request.setProgressListener(new ProgressListener() { @Override public void progressChanged(ProgressEvent progressEvent) { long bytesTransferred = progressEvent.getBytesTransferred(); long totalBytes = progressEvent.getTotalBytesToTransfer(); int type = progressEvent.getProgressType(); if (type == ProgressEvent.TRANSFER_COMPLETED_EVENT) { System.out.println("Upload completed"); } else if (type == ProgressEvent.REQUEST_BYTE_TRANSFER_EVENT) { double progress = (double) bytesTransferred / totalBytes * 100; System.out.printf("Progress: %.2f%%%n", progress); } } }); cosClient.putObject(request); ``` -------------------------------- ### Set and Get Bucket Versioning Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configures bucket versioning by setting its status to 'Enabled' using `SetBucketVersioningConfigurationRequest`. It also shows how to retrieve the current versioning configuration. ```java BucketVersioningConfiguration config = new BucketVersioningConfiguration(); config.setStatus(BucketVersioningConfiguration.ENABLED); SetBucketVersioningConfigurationRequest request = new SetBucketVersioningConfigurationRequest(bucketName, config); cosClient.setBucketVersioningConfiguration(request); // Retrieve versioning config BucketVersioningConfiguration currentConfig = cosClient.getBucketVersioningConfiguration(bucketName); System.out.println("Status: " + currentConfig.getStatus()); ``` -------------------------------- ### ClientExceptionConstants Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/04-Errors.md Illustrates common client-side error codes defined in ClientExceptionConstants. These constants can be used for programmatic checking of specific client errors. ```java public class ClientExceptionConstants { public static final String UNKNOWN = "Unknown"; public static final String REQUEST_TIMEOUT = "RequestTimeout"; // ... other constants } ``` -------------------------------- ### COSClient - Core API Reference Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/00-README.md The COSClient class is the main entry point for interacting with Tencent Cloud Object Storage. It provides methods for object operations (put, get, delete, copy, list), bucket operations (create, delete, list), and multipart upload operations. It contains over 100 methods for comprehensive management. ```APIDOC ## COSClient ### Description Provides methods for object and bucket management, including upload, download, deletion, copying, listing, creation, and multipart uploads. It is the primary client class for the SDK. ### Class COSClient ### Methods - **Object Operations**: putObject, getObject, deleteObject, copyObject, listObjects - **Bucket Operations**: createBucket, deleteBucket, listBuckets - **Multipart Upload Operations**: initiateMultipartUpload, uploadPart, completeMultipartUpload, abortMultipartUpload ### Notes Contains 100+ methods for full functionality. ``` -------------------------------- ### Get Async Fetch Task Status Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Use GetAsyncFetchTaskRequest to retrieve the status of an asynchronous fetch task. Provide the bucket name and task ID to get the task's code, message, and data. ```java GetAsyncFetchTaskRequest request = new GetAsyncFetchTaskRequest(bucketName); request.setTaskId(taskId); GetAsyncFetchTaskResult result = cosClient.getAsyncFetchTask(request); System.out.println("Code: " + result.getCode()); System.out.println("Message: " + result.getMessage()); System.out.println("Data: " + result.getData()); ``` -------------------------------- ### Get Endpoint Suffix Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured custom endpoint suffix. ```java public String getEndpointSuffix() ``` -------------------------------- ### Get Backoff Strategy Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the currently configured backoff strategy for retries. ```java public BackoffStrategy getBackoffStrategy() ``` -------------------------------- ### Get Retry Policy Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the currently configured retry policy for the client. ```java public RetryPolicy getRetryPolicy() ``` -------------------------------- ### Get Socket Timeout Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured timeout for socket read operations. ```java public int getSocketTimeout() ``` -------------------------------- ### Initialize COS Client Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Set up the COSClient by providing your Tencent Cloud credentials (SecretId and SecretKey) and region configuration. Ensure to shut down the client when done. ```java 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.region.Region; public class QuickStart { public static void main(String[] args) { // 1. Create credentials String secretId = "your-secret-id"; String secretKey = "your-secret-key"; COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 2. Set client config Region region = new Region("ap-beijing"); ClientConfig config = new ClientConfig(region); // 3. Create COS client COSClient cosClient = new COSClient(cred, config); // 4. Use the client try { // Your code here } finally { cosClient.shutdown(); } } } ``` -------------------------------- ### Get Connection Timeout Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured timeout for establishing a new connection. ```java public int getConnectionTimeout() ``` -------------------------------- ### Get HTTP Protocol Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the currently configured HTTP protocol version. ```java public HttpProtocol getHttpProtocol() ``` -------------------------------- ### Configure Static Website Hosting Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Enable static website hosting for a bucket by specifying the index and error documents. This allows the bucket to serve website content directly. ```java BucketWebsiteConfiguration website = new BucketWebsiteConfiguration(); website.setIndexDocumentSuffix("index.html"); website.setErrorDocument("error.html"); SetBucketWebsiteConfigurationRequest request = new SetBucketWebsiteConfigurationRequest(bucketName, website); cosClient.setBucketWebsiteConfiguration(request); ``` -------------------------------- ### Initialize COSClient with Credentials and Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Instantiate COSClient using COSCredentialsProvider and ClientConfig. Ensure you provide valid AWS-style credentials and configure client settings like region. ```java 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.region.Region; // ... COSCredentials cred = new BasicCOSCredentials("your-secret-id", "your-secret-key"); ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing")); COSClient cosClient = new COSClient(cred, clientConfig); ``` -------------------------------- ### ClientConfig() Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Creates a ClientConfig instance with all default values. ```APIDOC ## ClientConfig() ### Description Creates a `ClientConfig` with all default values. ### Constructor Signature ```java public ClientConfig() ``` ``` -------------------------------- ### Get Signature Signer Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the currently configured custom signature signer implementation. ```java public COSSigner getCosSigner() ``` -------------------------------- ### Get HTTP Proxy Port Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured port number of the HTTP proxy. ```java public int getHttpProxyPort() ``` -------------------------------- ### Create ClientConfig with Default Values Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Creates a ClientConfig instance using all default configuration values. ```java public ClientConfig() ``` -------------------------------- ### Get Connection Request Timeout Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured timeout for acquiring a connection from the pool. ```java public int getConnectionRequestTimeout() ``` -------------------------------- ### List Objects with Prefix and Delimiter Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Demonstrates how to list objects in a bucket, filtering by a prefix and using a delimiter to simulate a hierarchical structure. Sets a maximum number of keys to retrieve. ```java ListObjectsRequest request = new ListObjectsRequest(); request.setBucketName(bucketName); request.setPrefix("documents/"); request.setDelimiter("/"); request.setMaxKeys(100); ObjectListing listing = cosClient.listObjects(request); for (CosObjectSummary summary : listing.getObjectSummaries()) { System.out.println(summary.getKey()); } ``` -------------------------------- ### Handle CosClientException Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/04-Errors.md Example of catching a CosClientException, printing error details, and checking for timeout or retryability. ```java try { cosClient.putObject(bucketName, key, content); } catch (CosClientException e) { System.out.println("Client Error: " + e.getMessage()); System.out.println("Error Code: " + e.getErrorCode()); if (e.isRequestTimeout()) { System.out.println("Request timed out"); } if (e.isRetryable()) { // Implement retry logic } } ``` -------------------------------- ### Proxy Client Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Sets up the client to use an HTTP proxy, including specifying the proxy IP, port, and authentication credentials. ```java ClientConfig config = new ClientConfig(new Region("ap-beijing")); config.setHttpProxyIp("10.0.0.1"); config.setHttpProxyPort(8080); config.setProxyUsername("username"); config.setProxyPassword("password"); config.setUseBasicAuth(true); ``` -------------------------------- ### Get Signature Expiration Time Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured expiration time in seconds for request signatures. ```java public long getSignExpired() ``` -------------------------------- ### List Objects and Handle Truncation Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Demonstrates how to list objects in a bucket and retrieve the next batch if the results are truncated. Requires an initialized `cosClient` and a `bucketName`. ```java ObjectListing listing = cosClient.listObjects(bucketName); System.out.println("Objects: " + listing.getObjectSummaries().size()); System.out.println("Truncated: " + listing.isTruncated()); if (listing.isTruncated()) { listing = cosClient.listNextBatchOfObjects(listing); } ``` -------------------------------- ### Retrieve Symbolic Link Target Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Get the target key of a symbolic link using GetSymlinkRequest. ```java GetSymlinkRequest request = new GetSymlinkRequest(bucketName, "link/to/target"); GetSymlinkResult result = cosClient.getSymlink(request); System.out.println("Target: " + result.getTarget()); ``` -------------------------------- ### Get HTTP Proxy IP Address Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured IP address of the HTTP proxy. ```java public String getHttpProxyIp() ``` -------------------------------- ### Bucket Website Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configure static website hosting for a bucket, including index documents, error pages, and request routing. ```APIDOC ## Bucket Website Configuration ### Description Configure static website hosting for a bucket, including index documents, error pages, and request routing. ### Method - `setBucketWebsiteConfiguration(SetBucketWebsiteConfigurationRequest)`: Sets the website hosting configuration for a bucket. ### Request Example ```java BucketWebsiteConfiguration website = new BucketWebsiteConfiguration(); website.setIndexDocumentSuffix("index.html"); website.setErrorDocument("error.html"); SetBucketWebsiteConfigurationRequest request = new SetBucketWebsiteConfigurationRequest(bucketName, website); cosClient.setBucketWebsiteConfiguration(request); ``` ``` -------------------------------- ### Configure Bucket Logging Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Enable server access logging for a bucket to monitor access patterns. Specify the destination bucket and a prefix for log files. ```java BucketLoggingConfiguration logging = new BucketLoggingConfiguration(); logging.setDestinationBucketName("log-bucket-123456789"); logging.setLogFilePrefix("my-app-logs/"); SetBucketLoggingConfigurationRequest request = new SetBucketLoggingConfigurationRequest(bucketName, logging); cosClient.setBucketLoggingConfiguration(request); ``` -------------------------------- ### Get Idle Connection Alive Timeout Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the timeout duration for closing idle connections. ```java public int getIdleConnectionAlive() ``` -------------------------------- ### Get Maximum Connections Count Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the maximum number of connections permitted in the connection pool. ```java public int getMaxConnectionsCount() ``` -------------------------------- ### getCredentials() Method Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/03-Authentication.md Gets the current credentials. This method is called for each request or can be cached per configuration. ```java COSCredentials getCredentials() ``` -------------------------------- ### Create a Bucket Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Create a new bucket with a specified name. The bucket name must be globally unique. ```java import com.qcloud.cos.model.Bucket; String bucketName = "my-new-bucket-1234567890"; Bucket bucket = cosClient.createBucket(bucketName); System.out.println("Bucket created: " + bucket.getName()); ``` -------------------------------- ### Get Maximum Error Retry Count Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured maximum number of retries for regular requests. ```java public int getMaxErrorRetry() ``` -------------------------------- ### BasicSessionCredentials Constructor Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/08-Types.md Enables the creation of session credentials, which include an access key, secret key, and a session token. ```java public class BasicSessionCredentials implements COSCredentials { public BasicSessionCredentials(String accessKey, String secretKey, String sessionToken) } ``` -------------------------------- ### COSClient Constructor Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Initializes a new COSClient instance with provided credentials and client configuration. The credentials provider supplies authentication details, while the client config defines network and retry settings. ```APIDOC ## COSClient(COSCredentialsProvider credentialsProvider, ClientConfig clientConfig) ### Description Initializes a new COSClient instance with provided credentials and client configuration. The credentials provider supplies authentication details, while the client config defines network and retry settings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```java public COSClient(COSCredentialsProvider credentialsProvider, ClientConfig clientConfig) ``` ### Parameters - **credentialsProvider** (COSCredentialsProvider) - Required - Provides AWS-style credentials (SecretId and SecretKey) - **clientConfig** (ClientConfig) - Required - Configuration settings including region, timeouts, and retry policies ### Example ```java COSCredentials cred = new BasicCOSCredentials("your-secret-id", "your-secret-key"); ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing")); COSClient cosClient = new COSClient(cred, clientConfig); ``` ``` -------------------------------- ### Get Bucket Location Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Retrieves the region where a specified bucket is located. Ensure the bucket name is valid. ```java String bucketName = "my-bucket-1234567890"; String location = cosClient.getBucketLocation(bucketName); System.out.println("Location: " + location); ``` -------------------------------- ### Initiate Multipart Upload Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/00-README.md Use this snippet to initiate a multipart upload for large files. This is the first step before uploading parts and completing the upload. ```java InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, key); InitiateMultipartUploadResult initResult = cosClient.initiateMultipartUpload(initRequest); // ... upload parts, then complete ``` -------------------------------- ### Bucket Configuration Classes Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/00-README.md Documentation for classes related to bucket configurations, such as Access Control Lists (ACLs), versioning, lifecycle rules, and CORS settings. Covers over 30 configuration classes. ```APIDOC ## Bucket Configuration ### Description Provides classes for configuring various aspects of a bucket. ### Configuration Areas - **Access Control Lists (ACLs)**: Using CannedAccessControlList. - **Bucket Versioning**: BucketVersioningConfiguration. - **Lifecycle Rules**: BucketLifecycleConfiguration, Rule. - **CORS Configuration**: BucketCrossOriginConfiguration. - **Bucket Tagging**: BucketTaggingConfiguration. - **Other Configurations**: Logging, website, referer, encryption settings. ### Notes Includes 30+ configuration classes. ``` -------------------------------- ### Get Read Buffer Limit Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Retrieves the configured buffer limit in bytes for reading request and response bodies. ```java public int getReadLimit() ``` -------------------------------- ### Other Settings Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Configure miscellaneous settings such as read buffer limits. ```APIDOC ## setReadLimit(int readLimit) ### Description Set the buffer limit (in bytes) for reading request and response bodies. ### Method `public void setReadLimit(int readLimit)` ### Parameters #### Request Body - **readLimit** (int) - Required - The buffer limit in bytes. Default is 131073 (128KB). ``` ```APIDOC ## getReadLimit() ### Description Get the configured read limit for request and response bodies. ### Method `public int getReadLimit()` ### Returns - **int** - The read limit in bytes. ``` -------------------------------- ### Proxy Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Configure HTTP proxy settings, including IP, port, username, password, and whether to use basic authentication. ```APIDOC ## setUseBasicAuth(boolean useBasicAuth) ### Description Enable or disable basic authentication for proxy. ### Method `public void setUseBasicAuth(boolean useBasicAuth)` ### Parameters #### Request Body - **useBasicAuth** (boolean) - Required - Whether to enable basic authentication for the proxy. ``` ```APIDOC ## setHttpProxyIp(String httpProxyIp) ### Description Set the HTTP proxy IP address. ### Method `public void setHttpProxyIp(String httpProxyIp)` ### Parameters #### Request Body - **httpProxyIp** (String) - Required - The IP address of the HTTP proxy. ``` ```APIDOC ## setHttpProxyPort(int httpProxyPort) ### Description Set the HTTP proxy port. ### Method `public void setHttpProxyPort(int httpProxyPort)` ### Parameters #### Request Body - **httpProxyPort** (int) - Required - The port of the HTTP proxy. ``` ```APIDOC ## setProxyUsername(String proxyUsername) ### Description Set the username for proxy authentication. ### Method `public void setProxyUsername(String proxyUsername)` ### Parameters #### Request Body - **proxyUsername** (String) - Required - The username for proxy authentication. ``` ```APIDOC ## setProxyPassword(String proxyPassword) ### Description Set the password for proxy authentication. ### Method `public void setProxyPassword(String proxyPassword)` ### Parameters #### Request Body - **proxyPassword** (String) - Required - The password for proxy authentication. ``` -------------------------------- ### Handle Service and Client Exceptions Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Demonstrates how to catch and handle both service-side (e.g., NoSuchBucket) and client-side (e.g., network issues) exceptions during COS operations. Includes logic for retrying specific server errors. ```java import com.qcloud.cos.exception.CosClientException; import com.qcloud.cos.exception.CosServiceException; try { cosClient.putObject(bucketName, key, file); } catch (CosServiceException e) { // Service-side error (4xx, 5xx HTTP status) System.out.println("Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Error Message: " + e.getErrorMessage()); System.out.println("Request ID: " + e.getRequestId()); if (e.getErrorCode().equals("NoSuchBucket")) { System.out.println("Bucket does not exist"); } else if (e.getStatusCode() >= 500 && e.isRetryable()) { // Retry for server errors } } catch (CosClientException e) { // Client-side error (network, parsing, etc.) System.out.println("Client Error: " + e.getMessage()); e.printStackTrace(); } ``` -------------------------------- ### Set and Retrieve Bucket Tags Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configure tags for a bucket to organize resources. Tags can be set during bucket creation or updated later. Retrieved tags can be accessed as a map. ```java BucketTaggingConfiguration config = new BucketTaggingConfiguration(); TagSet tagSet = new TagSet(); tagSet.addTag("environment", "production"); tagSet.addTag("application", "myapp"); tagSet.addTag("cost-center", "engineering"); config.setTagSet(tagSet); SetBucketTaggingConfigurationRequest request = new SetBucketTaggingConfigurationRequest(bucketName, config); cosClient.setBucketTaggingConfiguration(request); // Retrieve tags BucketTaggingConfiguration retrievedConfig = cosClient.getBucketTaggingConfiguration(bucketName); Map tags = retrievedConfig.getTagSet().getTags(); ``` -------------------------------- ### Set Bucket Lifecycle Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configure rules for object expiration and storage class transitions. Ensure the bucket name and lifecycle configuration are correctly set. ```java BucketLifecycleConfiguration config = new BucketLifecycleConfiguration(); Rule rule = new Rule(); rule.setId("expire-logs"); rule.setStatus("Enabled"); LifecycleFilter filter = new LifecycleFilter(); filter.setPrefixAndTags(new LifecycleFilterAndOperator( "logs/", // prefix new HashMap<>() // tags )); rule.setFilter(filter); LifecycleExpiration expiration = new LifecycleExpiration(); expiration.setDays(90); rule.setExpiration(expiration); config.addRule(rule); SetBucketLifecycleConfigurationRequest request = new SetBucketLifecycleConfigurationRequest(bucketName, config); cosClient.setBucketLifecycleConfiguration(request); ``` -------------------------------- ### Set Custom Endpoint Suffix Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Applies a custom suffix to the endpoint URL, useful for private or customized domain setups (e.g., `.cos.mycompany.com`). ```java public void setEndpointSuffix(String endPointSuffix) ``` -------------------------------- ### createBucket(String bucketName) Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Creates a new bucket. The bucket name must be unique and include the APPID. The bucket will be created in the region configured in the ClientConfig. ```APIDOC ## createBucket(String bucketName) ### Description Create a new bucket in the region configured in `ClientConfig`. ### Method ```java public Bucket createBucket(String bucketName) ``` ### Parameters #### Path Parameters - **bucketName** (String) - Required - Unique bucket name with APPID (e.g., `my-bucket-1234567890`) ### Response #### Success Response - **Bucket** - Object representing the created bucket ### Example ```java Bucket bucket = cosClient.createBucket("my-new-bucket-1234567890"); System.out.println("Bucket created: " + bucket.getName()); ``` ``` -------------------------------- ### Set Bucket ACL Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Sets the Access Control List (ACL) for a bucket using `SetBucketAclRequest`. This example demonstrates setting a canned ACL, such as `Private`. ```java SetBucketAclRequest request = new SetBucketAclRequest(bucketName); request.setCannedAcl(CannedAccessControlList.Private); cosClient.setBucketAcl(request); ``` -------------------------------- ### ServiceExceptionConstants Example Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/04-Errors.md Shows common service-side error codes defined in ServiceExceptionConstants. These constants are useful for identifying specific errors returned by the COS service. ```java public class ServiceExceptionConstants { public static final String NO_SUCH_KEY = "NoSuchKey"; public static final String NO_SUCH_BUCKET = "NoSuchBucket"; public static final String ACCESS_DENIED = "AccessDenied"; // ... other constants } ``` -------------------------------- ### COSVersionSummary and KeyVersion for Versioned Buckets Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/08-Types.md These classes are relevant for versioned buckets. `COSVersionSummary` provides details about a specific object version, including its ID, whether it's a delete marker, key, size, and last modified date. `KeyVersion` represents a specific version of an object identified by its key and version ID. ```APIDOC ## Version IDs for Versioned Buckets ### Description Classes used to manage and retrieve information about object versions in versioned buckets. #### `COSVersionSummary` - **`getVersionId()`** (String) - Returns the unique version ID of the object. - **`isDeleteMarker()`** (boolean) - Returns `true` if this version is a delete marker, `false` otherwise. - **`getKey()`** (String) - Returns the key of the object. - **`getSize()`** (long) - Returns the size of the object version in bytes. - **`getLastModified()`** (Date) - Returns the last modified date of the object version. #### `KeyVersion` - **`getKey()`** (String) - Returns the key of the object. - **`getVersion()`** (String) - Returns the version ID of the object. ``` -------------------------------- ### Add Storage Class Transitions Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Define rules for transitioning objects to different storage classes after a specified number of days. Supports multiple transitions for a single rule. ```java StorageClassTransition transition = new StorageClassTransition(); transition.setDays(30); transition.setStorageClass("INTELLIGENT_TIERING"); rule.addStorageClassTransition(transition); // Archive after 90 days StorageClassTransition archiveTransition = new StorageClassTransition(); archiveTransition.setDays(90); archiveTransition.setStorageClass("ARCHIVE"); rule.addStorageClassTransition(archiveTransition); ``` -------------------------------- ### ObjectListing Class Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Represents the response from listing objects in a bucket. It contains lists of object summaries, common prefixes, and pagination information. ```APIDOC ## ObjectListing Class Response from listing objects. **Package:** `com.qcloud.cos.model` ### Methods | Method | Type | Description | |---|---|---| | `getObjectSummaries()` | List | List of `CosObjectSummary` | | `getCommonPrefixes()` | List | Common prefixes if delimiter used | | `isTruncated()` | boolean | Whether result is truncated | | `getMarker()` | String | Marker for pagination | | `getNextMarker()` | String | Next marker for next page | | `getMaxKeys()` | int | Max keys in request | | `getPrefix()` | String | Prefix in request | | `getDelimiter()` | String | Delimiter in request | #### Example ```java ObjectListing listing = cosClient.listObjects(bucketName); System.out.println("Objects: " + listing.getObjectSummaries().size()); System.out.println("Truncated: " + listing.isTruncated()); if (listing.isTruncated()) { listing = cosClient.listNextBatchOfObjects(listing); } ``` ``` -------------------------------- ### Download Object with Input Stream Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Download an object from COS and get its data as an input stream. Always close the input stream after use to free resources. ```java COSObject cosObject = cosClient.getObject(bucketName, key); try (InputStream is = cosObject.getObjectContent()) { // Read data from is } catch (IOException e) { e.printStackTrace(); } ``` -------------------------------- ### Bucket Logging Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configure server access logging for a bucket. This directs logs to a specified destination bucket with a defined prefix. ```APIDOC ## Bucket Logging Configuration ### Description Configure server access logging for a bucket. This directs logs to a specified destination bucket with a defined prefix. ### Method - `setBucketLoggingConfiguration(SetBucketLoggingConfigurationRequest)`: Sets the logging configuration for a bucket. ### Request Example ```java BucketLoggingConfiguration logging = new BucketLoggingConfiguration(); logging.setDestinationBucketName("log-bucket-123456789"); logging.setLogFilePrefix("my-app-logs/"); SetBucketLoggingConfigurationRequest request = new SetBucketLoggingConfigurationRequest(bucketName, logging); cosClient.setBucketLoggingConfiguration(request); ``` ``` -------------------------------- ### Get Bucket ACL Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Retrieves the Access Control List (ACL) for a specified bucket using `GetBucketAclRequest`. It then iterates through the grants to print grantee identifiers and permissions. ```java GetBucketAclRequest request = new GetBucketAclRequest(bucketName); AccessControlList acl = cosClient.getBucketAcl(request); List grants = acl.getGrantsAsList(); for (Grant grant : grants) { System.out.println("Grantee: " + grant.getGrantee().getIdentifier()); System.out.println("Permission: " + grant.getPermission()); } ``` -------------------------------- ### InstanceCredentialsProvider Constructor Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/03-Authentication.md Initializes an InstanceCredentialsProvider. This provider automatically fetches credentials from the instance metadata service, suitable for EC2 or container environments. ```java public InstanceCredentialsProvider() ``` ```java COSCredentialsProvider credProvider = new InstanceCredentialsProvider(); COSClient cosClient = new COSClient(credProvider, config); ``` -------------------------------- ### Retrieve Object Metadata Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Get an object's metadata, such as size and content type, without downloading the object's content. Useful for checking object properties. ```java ObjectMetadata metadata = cosClient.getObjectMetadata(bucketName, key); System.out.println("Size: " + metadata.getContentLength()); System.out.println("ETag: " + metadata.getETag()); ``` -------------------------------- ### Upload Object with Metadata Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Shows how to create an ObjectMetadata object and associate it with a PutObjectRequest for uploading an object with custom headers and content information. ```java ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("application/json"); metadata.setContentLength(1024); metadata.setCacheControl("max-age=3600"); metadata.setContentDisposition("inline"); metadata.addUserMetadata("department", "engineering"); metadata.addUserMetadata("project", "cos-sdk"); PutObjectRequest request = new PutObjectRequest(bucketName, key, inputStream, metadata); cosClient.putObject(request); ``` -------------------------------- ### Create Bucket Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Create a new bucket in Tencent Cloud Object Storage. The bucket name must be globally unique and include the APPID. ```java Bucket bucket = cosClient.createBucket("my-new-bucket-1234567890"); System.out.println("Bucket created: " + bucket.getName()); ``` -------------------------------- ### InitiateMultipartUploadRequest Class Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Represents a request to initiate a multipart upload for an object. It includes the bucket name, object key, and optional object metadata or ACL. ```APIDOC ## InitiateMultipartUploadRequest Class Request to initiate a multipart upload. **Package:** `com.qcloud.cos.model` ### Methods | Method | Description | |---|---| | `getBucketName()` / `setBucketName(String)` | Bucket name | | `getKey()` / `setKey(String)` | Object key | | `setObjectMetadata(ObjectMetadata)` | Metadata for final object | | `setCannedAcl(CannedAccessControlList)` | ACL for final object | #### Example ```java InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest( bucketName, "large-file.zip"); InitiateMultipartUploadResult result = cosClient.initiateMultipartUpload(request); String uploadId = result.getUploadId(); ``` ``` -------------------------------- ### Set Lifecycle Configuration for Objects Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Define rules to automatically expire or transition objects after a specified period. This example sets a rule to expire logs older than 90 days. ```java import com.qcloud.cos.model.*; import com.qcloud.cos.model.lifecycle.*; BucketLifecycleConfiguration config = new BucketLifecycleConfiguration(); Rule rule = new Rule(); rule.setId("expire-old-logs"); rule.setStatus("Enabled"); LifecycleFilter filter = new LifecycleFilter(); filter.setPrefixAndTags(new LifecycleFilterAndOperator("logs/")); rule.setFilter(filter); LifecycleExpiration expiration = new LifecycleExpiration(); expiration.setDays(90); rule.setExpiration(expiration); config.addRule(rule); SetBucketLifecycleConfigurationRequest request = new SetBucketLifecycleConfigurationRequest(bucketName, config); cosClient.setBucketLifecycleConfiguration(request); ``` -------------------------------- ### GetObjectRequest Constructor Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Shows the basic constructor for creating a GetObjectRequest to download an object. ```java public GetObjectRequest(String bucketName, String key) ``` -------------------------------- ### Handling CosServiceException and CosClientException Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/04-Errors.md Catch and inspect CosServiceException for server-side errors and CosClientException for client-side issues. This example shows how to extract status codes, error codes, messages, and request IDs. ```java try { cosClient.getObject(bucketName, "nonexistent.txt"); } catch (CosServiceException e) { System.out.println("Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Error Message: " + e.getErrorMessage()); System.out.println("Request ID: " + e.getRequestId()); if (e.getErrorCode().equals("NoSuchKey")) { System.out.println("Object not found"); } else if (e.getStatusCode() >= 500 && e.isRetryable()) { // Implement retry } } catch (CosClientException e) { System.out.println("Client Error: " + e.getMessage()); } ``` -------------------------------- ### Transfer Manager Management Methods Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/07-Advanced.md Provides methods to access the underlying COS client, wait for transfer completion, check status, get progress, pause, resume, and shut down the Transfer Manager. ```java public COS getAmazonCOS() public void waitForCompletion() throws InterruptedException public boolean isDone() public TransferProgress getProgress() public PersistableTransfer pause() public void resume() public void shutdown() ``` -------------------------------- ### Bucket Referer Configuration Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configure hotlink protection for a bucket using referer headers. Specify allowed or denied referer domains. ```APIDOC ## Bucket Referer Configuration ### Description Configure hotlink protection for a bucket using referer headers. Specify allowed or denied referer domains. ### Method - `setBucketRefererConfiguration(SetBucketRefererConfigurationRequest)`: Sets the referer configuration for a bucket. ### Request Example ```java BucketRefererConfiguration referer = new BucketRefererConfiguration(); referer.setRefererType("White-list"); referer.setEmptyReferConfiguration("Deny"); referer.setDomainList(Arrays.asList("https://example.com", "https://app.example.com")); SetBucketRefererConfigurationRequest request = new SetBucketRefererConfigurationRequest(bucketName, referer); cosClient.setBucketRefererConfiguration(request); ``` ``` -------------------------------- ### List Objects with Advanced Options Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Lists objects using advanced options such as delimiter, max-keys, and marker for fine-grained control over pagination and filtering. It can also retrieve common prefixes. ```java ListObjectsRequest request = new ListObjectsRequest(); request.setBucketName(bucketName); request.setPrefix("documents/"); request.setDelimiter("/"); request.setMaxKeys(100); ObjectListing listing = cosClient.listObjects(request); List commonPrefixes = listing.getCommonPrefixes(); ``` -------------------------------- ### ClientConfig - Configuration Class Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/00-README.md The ClientConfig class allows customization of the SDK's behavior, including region and protocol settings, connection timeouts, proxy configuration, and retry policies. It offers over 40 configuration properties for fine-grained control. ```APIDOC ## ClientConfig ### Description Manages configuration settings for the COS client, including network parameters, security, and retry logic. ### Class ClientConfig ### Properties - **Region**: Geographic region for the COS service. - **Protocol**: HTTP or HTTPS. - **Timeouts**: Connection and socket timeouts. - **Proxy**: Proxy server configuration. - **Retry Policies**: Strategies for retrying failed requests. - **Credentials**: Configuration for request signing and authentication. ### Notes Contains 40+ configuration properties. ``` -------------------------------- ### StorageClassTransition Class Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Configures transitions of objects between different storage classes. ```APIDOC ## StorageClassTransition Class Transition objects between storage classes. ### Methods - **`setDays(int days)`**: Sets the number of days after which the transition should occur. - **`setDate(Date date)`**: Sets a specific date for the transition. - **`setStorageClass(String storageClass)`**: Sets the target storage class for the transition. Supported classes include: - `STANDARD` - `INTELLIGENT_TIERING` - `STANDARD_IA` - `ARCHIVE` - `DEEP_ARCHIVE` ``` -------------------------------- ### Configure Bucket Referer Protection Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/06-BucketConfiguration.md Implement hotlink protection for a bucket by configuring referer rules. This prevents unauthorized access to your bucket's content from other websites. ```java BucketRefererConfiguration referer = new BucketRefererConfiguration(); referer.setRefererType("White-list"); referer.setEmptyReferConfiguration("Deny"); referer.setDomainList(Arrays.asList( "https://example.com", "https://app.example.com" )); SetBucketRefererConfigurationRequest request = new SetBucketRefererConfigurationRequest(bucketName, referer); cosClient.setBucketRefererConfiguration(request); ``` -------------------------------- ### Bucket Configuration Operations Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Provides methods for configuring bucket settings such as ACL, versioning, lifecycle, CORS, and tagging. ```APIDOC ## Bucket Configuration Operations ### Description The `COSClient` also provides methods for bucket configuration: - `setBucketAcl(String, CannedAccessControlList)` — Set bucket ACL - `getBucketAcl(String)` — Get bucket ACL - `setBucketVersioningConfiguration(SetBucketVersioningConfigurationRequest)` — Enable/suspend versioning - `getBucketVersioningConfiguration(String)` — Get versioning configuration - `setBucketLifecycleConfiguration(String, BucketLifecycleConfiguration)` — Set lifecycle rules - `getBucketLifecycleConfiguration(String)` — Get lifecycle configuration - `setBucketCorsConfiguration(String, BucketCrossOriginConfiguration)` — Set CORS rules - `getBucketCorsConfiguration(String)` — Get CORS configuration - `setBucketTaggingConfiguration(String, BucketTaggingConfiguration)` — Set bucket tags - `getBucketTaggingConfiguration(String)` — Get bucket tags ``` -------------------------------- ### List All Buckets Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Retrieve a list of all buckets associated with your Tencent Cloud account. ```java import java.util.List; List buckets = cosClient.listBuckets(); for (Bucket bucket : buckets) { System.out.println("Name: " + bucket.getName()); System.out.println("Created: " + bucket.getCreationDate()); } ``` -------------------------------- ### Enable Basic Authentication for Proxy Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/02-ClientConfig.md Enables basic authentication for HTTP proxy connections. Ensure proxy IP, port, username, and password are set. ```java config.setHttpProxyIp("proxy.example.com"); config.setHttpProxyPort(8080); config.setProxyUsername("user"); config.setProxyPassword("pass"); config.setUseBasicAuth(true); ``` -------------------------------- ### PutObjectRequest Constructors Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/05-RequestResponse.md Demonstrates the different ways to construct a PutObjectRequest for uploading objects. ```java public PutObjectRequest(String bucketName, String key, File file) public PutObjectRequest(String bucketName, String key, InputStream input) public PutObjectRequest(String bucketName, String key, String content) ``` -------------------------------- ### Enable Bucket Versioning Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/09-GettingStarted.md Activate versioning for a bucket to protect against accidental overwrites and deletions. This ensures that previous versions of objects are retained. ```java import com.qcloud.cos.model.BucketVersioningConfiguration; import com.qcloud.cos.model.SetBucketVersioningConfigurationRequest; BucketVersioningConfiguration config = new BucketVersioningConfiguration(); config.setStatus(BucketVersioningConfiguration.ENABLED); SetBucketVersioningConfigurationRequest request = new SetBucketVersioningConfigurationRequest(bucketName, config); cosClient.setBucketVersioningConfiguration(request); ``` -------------------------------- ### List Objects with Prefix Source: https://github.com/tencentyun/cos-java-sdk-v5/blob/master/_autodocs/01-COSClient.md Filters objects in a bucket by a specified key prefix. This is useful for retrieving objects within a specific directory or with a common naming pattern. ```java ObjectListing listing = cosClient.listObjects(bucketName, "documents/"); ```