简介
本文档提供快捷查询某个存储桶是否存在的示例代码。
HeadBucket除了检查存储桶是否存在,还可以判断是否有权限访问存储桶,有以下几种情况:
存储桶存在且有读取权限,返回 HTTP 状态码为200。
无存储桶读取权限,返回 HTTP 状态码为403。
存储桶不存在,返回 HTTP 状态码为404。
注意事项
在您使用存储桶相关操作之前,需要先具有相关权限:
相关示例
功能名称 | 描述 | 示例代码 |
判断存储桶是否存在 | 查询存储桶是否存在 |
前期准备
使用永久密钥创建 CosAPI
调用 COS 的接口之前,必须先创建一个 CosAPI 的实例,用于后续调用请求。
qcloud_cos::CosAPI InitCosAPI() {uint64_t appid = 12500000000;std::string region = "ap-guangzhou";// bucket 的地域,请参见 https://cloud.tencent.com/document/product/436/62std::string secret_id = "************************************"; //用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140std::string secret_key = "************************************"; //用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);qcloud_cos::CosAPI cos_tmp(config);return cos_tmp;}
使用临时密钥创建 CosAPI
如果要使用临时密钥请求 COS,则需要用临时密钥创建 CosAPI 实例。
qcloud_cos::CosAPI InitCosAPI() {// 需要已经获取到临时密钥的结果:tmp_secret_id、tmp_secret_key、// 临时密钥的生成参见 https://cloud.tencent.com/document/product/436/14048#cos-sts-sdkuint64_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;}
使用案例:检查存储桶是否存在
通过 SDK 提供的快捷接口来检查 Bucket 是否存在。
方法原型
bool CosAPI::IsBucketExist(const std::string& bucket_name)
请求示例
void IsBucketExist(qcloud_cos::CosAPI& cos) {std::cout << "===================IsBucketExist====================="<< std::endl;std::cout << (cos.IsBucketExist("abcdefg") ? "true" : "false") << std::endl;std::cout << (cos.IsBucketExist(bucket_name) ? "true" : "false") << std::endl;std::cout<< "===================================================================="<< std::endl;}
参数说明
参数名称 | 描述 | 类型 |
bucket_name | 存储桶名称 | string |
返回结果说明
成功则返回 bool 类型:true 代表存在,false 代表不存在。