tencent cloud

Cloud Object Storage

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Features
Use Cases
Strengths
Concepts
Regions and Access Endpoints
Specifications and Limits
Service Regions and Service Providers
Billing
Billing Overview
Billing Method
Billable Items
Free Tier
Billing Examples
Viewing and Downloading Bill
Payment Overdue
FAQs
Getting Started
Console
Getting Started with COSBrowser
User Guide
Creating Request
Bucket
Object
Data Management
Batch Operation
Global Acceleration
Monitoring and Alarms
Operations Center
Data Processing
Content Moderation
Smart Toolbox
Data Processing Workflow
Application Integration
User Tools
Tool Overview
Installation and Configuration of Environment
COSBrowser
COSCLI (Beta)
COSCMD
COS Migration
FTP Server
Hadoop
COSDistCp
HDFS TO COS
GooseFS-Lite
Online Tools
Diagnostic Tool
Use Cases
Overview
Access Control and Permission Management
Performance Optimization
Accessing COS with AWS S3 SDK
Data Disaster Recovery and Backup
Domain Name Management Practice
Image Processing
Audio/Video Practices
Workflow
Direct Data Upload
Content Moderation
Data Security
Data Verification
Big Data Practice
COS Cost Optimization Solutions
Using COS in the Third-party Applications
Migration Guide
Migrating Local Data to COS
Migrating Data from Third-Party Cloud Storage Service to COS
Migrating Data from URL to COS
Migrating Data Within COS
Migrating Data Between HDFS and COS
Data Lake Storage
Cloud Native Datalake Storage
Metadata Accelerator
GooseFS
Data Processing
Data Processing Overview
Image Processing
Media Processing
Content Moderation
File Processing Service
File Preview
Troubleshooting
Obtaining RequestId
Slow Upload over Public Network
403 Error for COS Access
Resource Access Error
POST Object Common Exceptions
API Documentation
Introduction
Common Request Headers
Common Response Headers
Error Codes
Request Signature
Action List
Service APIs
Bucket APIs
Object APIs
Batch Operation APIs
Data Processing APIs
Job and Workflow
Content Moderation APIs
Cloud Antivirus API
SDK Documentation
SDK Overview
Preparations
Android SDK
C SDK
C++ SDK
.NET(C#) SDK
Flutter SDK
Go SDK
iOS SDK
Java SDK
JavaScript SDK
Node.js SDK
PHP SDK
Python SDK
React Native SDK
Mini Program SDK
Error Codes
Harmony SDK
Endpoint SDK Quality Optimization
Security and Compliance
Data Disaster Recovery
Data Security
Cloud Access Management
FAQs
Popular Questions
General
Billing
Domain Name Compliance Issues
Bucket Configuration
Domain Names and CDN
Object Operations
Logging and Monitoring
Permission Management
Data Processing
Data Security
Pre-signed URL Issues
SDKs
Tools
APIs
Agreements
Service Level Agreement
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Generate a Presigned URL

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-03-05 17:01:25

Introduction

This article introduces sample code and a description for generating pre-signed URLs for objects using the C++ SDK for COS.

Must-Knows

Buckets created after January 1, 2024 do not support previewing files in the browser using the default domain. It is recommended that you configure a custom domain. For details, see Bucket Switching to Custom Domain.
Generating pre-signed URLs supports the use of permanent keys or temporary keys.
Obtain the signature/pre-signature function, which by default signs the Host Header. You can choose not to sign the Host Header, but this may cause request failures or security vulnerabilities.

Related Examples

Function Name
Description
Example code
Generate a Presigned URL
Cloud Object Storage (COS) supports using pre-signed URLs for object uploads and downloads. The principle involves embedding the signature into the URL to generate a signed link.

Preliminary Preparation

Create CosAPI

Before the COS API is called, you must first create an instance of CosAPI to make subsequent call requests.
qcloud_cos::CosAPI InitCosAPI() {
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";// Region of the bucket, see https://www.tencentcloud.com/document/product/436/62?from_cn_redirect=1
std::string secret_id = "************************************"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
std::string secret_key = "************************************"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Create CosAPI Using a Temporary Key

To access COS with a temporary key, you need to create a CosAPI instance using the temporary key.
qcloud_cos::CosAPI InitCosAPI() {
// You need to have obtained the temporary key results: tmp_secret_id, tmp_secret_key,
// For generating temporary keys, see https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1#cos-sts-sdk
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";
std::string tmp_secret_id = "************************************";
std::string tmp_secret_key = "************************************";
std::string tmp_token = "token";
qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
config.SetTmpToken(tmp_token);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Use Cases

Generate a Presigned URL

Method Prototype

std::string CosAPI::GeneratePresignedUrl(const GeneratePresignedUrlReq& req)

Request Example

void GeneratePresignedUrlDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "test.txt";
qcloud_cos::GeneratePresignedUrlReq req(bucket_name, object_name, qcloud_cos::HTTP_GET); // The request method can be set.
// The following code block is optional. By default, the signature takes effect starting from the local current time, with a default validity period of 60s.
{
req.SetHttps(); // whether to use https
uint64_t start_time_in_s = time(NULL);
req.SetStartTimeInSec(start_time_in_s); // Sets the start time when the signature takes effect
req.SetExpiredTimeInSec(60); // Sets the validity period of the signature
}
std::string presigned_url = cos.GeneratePresignedUrl(req);

std::cout << "===================GeneratePresignedUrl=====================" << std::endl;
std::cout << "Presigend Url=[" << presigned_url << "]" << std::endl;
std::cout << "============================================================" << std::endl;
}

Parameter Description

Description of GeneratePresignedUrlReq members and functions:
Parameter Name
Description
Parameter Type
bucket_name
The bucket name follows the format BucketName-APPID. For details, see Naming Conventions
string
object_name
An object key is a unique identifier for an object in a bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg The object key is doc/picture.jpg. For details, see Object Key
string
method
HTTP methods, optional: HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE, HTTP_HEAD
string
SetHTTPS
Set to enable HTTPS; if not set, defaults to HTTP.
None
SetStartTimeInSec
Set the start time when the signature takes effect.
uint64_t
SetExpiredTimeInSec
Set the validity period of the signature.
uint64_t
SetSignHeaderHost
Whether to include the Host header (recommended), defaults to true
bool

Return Result Description

Returns the object pre-signed URL.

Generate a Pre-Signed Upload URL and Use It to Upload the Object

Note:
This example only demonstrates the network library used by the C++ SDK.

Request Example

// Include the following header files
#include "cos_defines.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/StreamCopier.h"
#include "Poco/URI.h"

void GeneratePresignedUrlAndPutObjectDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "test.txt";
qcloud_cos::GeneratePresignedUrlReq req(bucket_name, object_name, qcloud_cos::HTTP_PUT); // The request method can be set.
// The following code block is optional to set. By default, the signature takes effect starting from the local current time, with a default validity period of 60s.
{
req.SetUseHttps(false); // whether to use https
uint64_t start_time_in_s = time(NULL);
req.SetStartTimeInSec(start_time_in_s); // Sets the start time when the signature takes effect
req.SetExpiredTimeInSec(60); // Sets the validity period of the signature
}
std::string url_str = cos.GeneratePresignedUrl(req);
std::cout << "===================GeneratePresignedUrl=====================" << std::endl;
std::cout << "Presigend Url=[" << url_str << "]" << std::endl;
std::cout << "============================================================" << std::endl;

Poco::Net::HTTPResponse res;
int retryIndex = 0;
while (true) {
try {
std::cout << "send request to [" << url_str.c_str() << "]" << std::endl;
Poco::URI url(url_str);
std::string path = url.getPathAndQuery();
std::unique_ptr<Poco::Net::HTTPClientSession> session;
session.reset(new Poco::Net::HTTPClientSession(url.getHost(), url.getPort()));
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_PUT, path, Poco::Net::HTTPMessage::HTTP_1_1);
std::istringstream is("put object with PresignedUrl");
std::streampos pos = is.tellg();
is.seekg(0, std::ios::end);
req.setContentLength(is.tellg());
is.seekg(pos);
std::ostringstream debug_os;
req.write(debug_os);
std::cout << "request=[" << debug_os.str().c_str() << "]" << std::endl;
std::ostream& os = session->sendRequest(req);
std::streamsize copy_size = HandleStreamCopier::handleCopyStream(nullptr, is, os);
Poco::Net::StreamSocket& ss = session->socket();
std::istream& recv_stream = session->receiveResponse(res);
int response_code = res.getStatus();
// Retry on 5xx errors up to 3 times
if (response_code / 100 != 5 || retryIndex >= 3) {
std::cout << "Send request over, status=" << res.getStatus() << ", reason=" << res.getReason().c_str() << std::endl;
break;
}
std::cout << "will retry, retryIndex: " << retryIndex << std::endl;
retryIndex++;
} catch (const std::exception& ex) {
SDK_LOG_ERR("Exception:%s, errno=%d", std::string(ex.what()).c_str(), errno);
break;
}
}
}


Ajuda e Suporte

Esta página foi útil?

comentários