get_bucket_demo.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdlib.h>
  2. #include <sys/stat.h>
  3. #include <iostream>
  4. #include <map>
  5. #include <string>
  6. #include <thread>
  7. #include <vector>
  8. #include "cos_api.h"
  9. #include "cos_sys_config.h"
  10. #include "util/auth_tool.h"
  11. /**
  12. * 本样例演示了如何使用 COS C++ SDK 进行存储桶列表的获取
  13. */
  14. using namespace qcloud_cos;
  15. uint64_t appid = 12500000000;
  16. std::string tmp_secret_id = "AKIDXXXXXXXX";
  17. std::string tmp_secret_key = "1A2Z3YYYYYYYYYY";
  18. std::string region = "ap-guangzhou";
  19. std::string bucket_name = "examplebucket-12500000000";
  20. std::string tmp_token = "token";
  21. /*
  22. * 本方法包含调用是否正常的判断,和请求结果的输出
  23. * 可通过本方法判断是否请求成功,并输出结果信息
  24. */
  25. void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
  26. if (result.IsSucc()) {
  27. std::cout << "Request Succ." << std::endl;
  28. std::cout << resp.DebugString() << std::endl;
  29. } else {
  30. std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
  31. std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
  32. std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
  33. std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
  34. std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
  35. std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
  36. std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
  37. }
  38. }
  39. /*
  40. * 通过参数形式初始化 CosAPI 对象
  41. */
  42. qcloud_cos::CosAPI InitCosAPI() {
  43. qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
  44. config.SetTmpToken(tmp_token); // 推荐使用临时密钥初始化 CosAPI 对象, 如果您使用永久密钥初始化 CosAPI 对象,请注释
  45. qcloud_cos::CosAPI cos_tmp(config);
  46. return cos_tmp;
  47. }
  48. void GetBucket(qcloud_cos::CosAPI& cos) {
  49. qcloud_cos::GetBucketReq req(bucket_name);
  50. qcloud_cos::GetBucketResp resp;
  51. qcloud_cos::CosResult result = cos.GetBucket(req, &resp);
  52. std::cout << "===================GetBucket=====================" << std::endl;
  53. std::vector<qcloud_cos::Content> cotents = resp.GetContents();
  54. for (std::vector<qcloud_cos::Content>::const_iterator itr = cotents.begin(); itr != cotents.end(); ++itr) {
  55. const qcloud_cos::Content& content = *itr;
  56. std::cout << "key name=" << content.m_key << ", lastmodified ="
  57. << content.m_last_modified << ", size=" << content.m_size << std::endl;
  58. }
  59. PrintResult(result, resp);
  60. std::cout << "=========================================================" << std::endl;
  61. }
  62. int main() {
  63. qcloud_cos::CosAPI cos = InitCosAPI();
  64. CosSysConfig::SetLogLevel((LOG_LEVEL)COS_LOG_ERR);
  65. GetBucket(cos);
  66. }