计算
弹性云服务器 ECS
Flexus云服务
裸金属服务器 BMS
弹性伸缩 AS
镜像服务 IMS
专属主机 DeH
函数工作流 FunctionGraph
云手机服务器 CPH
Huawei Cloud EulerOS
网络
虚拟私有云 VPC
弹性公网IP EIP
虚拟专用网络 VPN
弹性负载均衡 ELB
NAT网关 NAT
云专线 DC
VPC终端节点 VPCEP
云连接 CC
企业路由器 ER
企业交换机 ESW
全球加速 GA
安全与合规
安全技术与应用
Web应用防火墙 WAF
企业主机安全 HSS
云防火墙 CFW
安全云脑 SecMaster
DDoS防护 AAD
数据加密服务 DEW
数据库安全服务 DBSS
云堡垒机 CBH
数据安全中心 DSC
云证书管理服务 CCM
边缘安全 EdgeSec
态势感知 SA
威胁检测服务 MTD
CDN与智能边缘
内容分发网络 CDN
CloudPond云服务
智能边缘云 IEC
迁移
主机迁移服务 SMS
对象存储迁移服务 OMS
云数据迁移 CDM
迁移中心 MGC
大数据
MapReduce服务 MRS
数据湖探索 DLI
表格存储服务 CloudTable
云搜索服务 CSS
数据接入服务 DIS
数据仓库服务 GaussDB(DWS)
数据治理中心 DataArts Studio
数据可视化 DLV
数据湖工厂 DLF
湖仓构建 LakeFormation
企业应用
云桌面 Workspace
应用与数据集成平台 ROMA Connect
云解析服务 DNS
专属云
专属计算集群 DCC
IoT物联网
IoT物联网
设备接入 IoTDA
智能边缘平台 IEF
用户服务
账号中心
费用中心
成本中心
资源中心
企业管理
工单管理
国际站常见问题
ICP备案
我的凭证
支持计划
客户运营能力
合作伙伴支持计划
专业服务
区块链
区块链服务 BCS
Web3节点引擎服务 NES
解决方案
SAP
高性能计算 HPC
视频
视频直播 Live
视频点播 VOD
媒体处理 MPC
实时音视频 SparkRTC
数字内容生产线 MetaStudio
存储
对象存储服务 OBS
云硬盘 EVS
云备份 CBR
存储容灾服务 SDRS
高性能弹性文件服务 SFS Turbo
弹性文件服务 SFS
云硬盘备份 VBS
云服务器备份 CSBS
数据快递服务 DES
专属分布式存储服务 DSS
容器
云容器引擎 CCE
容器镜像服务 SWR
应用服务网格 ASM
华为云UCS
云容器实例 CCI
管理与监管
云监控服务 CES
统一身份认证服务 IAM
资源编排服务 RFS
云审计服务 CTS
标签管理服务 TMS
云日志服务 LTS
配置审计 Config
资源访问管理 RAM
消息通知服务 SMN
应用运维管理 AOM
应用性能管理 APM
组织 Organizations
优化顾问 OA
IAM 身份中心
云运维中心 COC
资源治理中心 RGC
应用身份管理服务 OneAccess
数据库
云数据库 RDS
文档数据库服务 DDS
数据管理服务 DAS
数据复制服务 DRS
云数据库 GeminiDB
云数据库 GaussDB
分布式数据库中间件 DDM
数据库和应用迁移 UGO
云数据库 TaurusDB
人工智能
人脸识别服务 FRS
图引擎服务 GES
图像识别 Image
内容审核 Moderation
文字识别 OCR
AI开发平台ModelArts
图像搜索 ImageSearch
对话机器人服务 CBS
华为HiLens
视频智能分析服务 VIAS
语音交互服务 SIS
应用中间件
分布式缓存服务 DCS
API网关 APIG
微服务引擎 CSE
分布式消息服务Kafka版
分布式消息服务RabbitMQ版
分布式消息服务RocketMQ版
多活高可用服务 MAS
事件网格 EG
企业协同
华为云会议 Meeting
云通信
消息&短信 MSGSMS
云生态
合作伙伴中心
云商店
开发者工具
SDK开发指南
API签名指南
Terraform
华为云命令行工具服务 KooCLI
其他
产品价格详情
系统权限
管理控制台
客户关联华为云合作伙伴须知
消息中心
公共问题
开发与运维
应用管理与运维平台 ServiceStage
软件开发生产线 CodeArts
需求管理 CodeArts Req
部署 CodeArts Deploy
性能测试 CodeArts PerfTest
编译构建 CodeArts Build
流水线 CodeArts Pipeline
制品仓库 CodeArts Artifact
测试计划 CodeArts TestPlan
代码检查 CodeArts Check
代码托管 CodeArts Repo
云应用引擎 CAE
开天aPaaS
云消息服务 KooMessage
云手机服务 KooPhone
云空间服务 KooDrive
文档首页/ 对象存储服务 OBS/ 快速入门/ 通过OBS SDK快速使用OBS

通过OBS SDK快速使用OBS

更新时间:2024-09-29 GMT+08:00

OBS SDK对OBS服务提供的REST API进行封装,以简化用户的开发工作。您直接调用OBS SDK提供的接口函数即可使用OBS管理数据。

本章节以Java、Python、Go三种SDK为例,帮助您快速上手OBS的基础功能,包括创建桶、上传对象、下载对象、列举对象。

准备工作

使用Java SDK之前,您需要拥有一个华为账号并实名认证、为账号充值,接着获取访问密钥、准备开发环境,然后下载并安装Java SDK。

  1. 注册华为账号并实名认证。

    如果您已有华为账号,请忽略此步骤。如果您还没有华为账号,请执行以下操作:

    1. 注册华为账号并开通华为云
    2. 参考个人账号如何完成实名认证或,完成个人或企业账号实名认证。

  2. 为账号充值。

    您需要确保账号有足够的余额,才能正常使用OBS等相关资源。请参考账户充值

  3. 获取访问密钥,详情请参见获取访问密钥(AK和SK)
  4. 准备开发环境,详情请参见准备开发环境
  5. 下载与安装Java SDK,详情请参见下载与安装Java SDK

步骤一:创建桶

本示例用于创建名为examplebucket的桶,并设置所在区域在中国-香港(ap-southeast-1),桶的权限访问控制策略是私有桶,将存储类别设置为标准存储,数据冗余策略选择多AZ存储。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AccessControlList;
import com.obs.services.model.AvailableZoneEnum;
import com.obs.services.model.CreateBucketRequest;
import com.obs.services.model.ObsBucket;
import com.obs.services.model.StorageClassEnum;

public class CreateBucket001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");

        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";

        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        
        try {
            CreateBucketRequest request = new CreateBucketRequest();
            //示例桶名
            String exampleBucket = "examplebucket";
            //示例桶区域位置
            String exampleLocation = "ap-southeast-1";
            request.setBucketName(exampleBucket);
            // 设置桶访问权限为私有读写,默认也是私有读写
            request.setAcl(AccessControlList.REST_CANNED_PRIVATE);
            // 设置桶的存储类别为标准存储
            request.setBucketStorageClass(StorageClassEnum.STANDARD);
            // 设置桶区域位置(以区域为中国-香港为例),location 需要与 endpoint的位置信息一致
            request.setLocation(exampleLocation);
            // 指定创建多AZ桶,如果不设置,默认创建单AZ桶
            request.setAvailableZone(AvailableZoneEnum.MULTI_AZ);
            // 创建桶
            ObsBucket bucket = obsClient.createBucket(request);
            // 创建桶成功
            System.out.println("CreateBucket successfully");
            System.out.println("RequestId:"+bucket.getRequestId());


        } catch (ObsException e) {
            System.out.println("CreateBucket failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code: " + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message: " + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
        } catch (Exception e) {
            System.out.println("CreateBucket failed");
            // 其他异常信息打印
            e.printStackTrace();

        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from obs import CreateBucketHeader, HeadPermission
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 创建桶的附加头域,桶的访问控制策略是私有桶,存储类型是标准存储,多AZ方式存储
    header = CreateBucketHeader(aclControl=HeadPermission.PRIVATE, storageClass="STANDARD", availableZone="3az")
    # 指定存储桶所在区域,此处以“ap-southeast-1”为例,必须跟传入的Endpoint中Region保持一致。
    location = "ap-southeast-1"
    # 指定存储桶所在区域,必须跟传入的endpoint所在的region保持一致
    location = "region"
    bucketName = "examplebucket"
    # 创建桶
    resp = obsClient.createBucket(bucketName, header, location)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Create Bucket Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Create Bucket Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Create Bucket Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.CreateBucketInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定存储桶所在区域,此处以“ap-southeast-1”为例,必须跟传入的Endpoint中Region保持一致。
    input.Location = "ap-southeast-1"
    // 指定存储桶所在区域,必须跟传入的Endpoint中Region保持一致。
    input.Location = "region"
    // 指定存储桶的权限控制策略,此处以obs.AclPrivate为例。
    input.ACL = obs.AclPrivate
    // 指定存储桶的存储类型,此处以obs.StorageClassWarm为例。如果未指定该参数,则创建的桶为标准存储类型。
    input.StorageClass = obs.StorageClassWarm
    // 指定存储桶的AZ类型,此处以“3AZ”为例。不携带时默认为单AZ,如果对应region不支持多AZ存储,则该桶的存储类型仍为单AZ。
    input.AvailableZone = "3az"
    // 创建桶
    output, err := obsClient.CreateBucket(input)
    if err == nil {
        fmt.Printf("Create bucket:%s successful!\n", input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        return
    }
    fmt.Printf("Create bucket:%s fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AccessControlList;
import com.obs.services.model.AvailableZoneEnum;
import com.obs.services.model.CreateBucketRequest;
import com.obs.services.model.ObsBucket;
import com.obs.services.model.StorageClassEnum;

public class CreateBucket001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");

        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";

        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        
        try {
            CreateBucketRequest request = new CreateBucketRequest();
            //示例桶名
            String exampleBucket = "examplebucket";
            //示例桶区域位置
            String exampleLocation = "ap-southeast-1";
            request.setBucketName(exampleBucket);
            // 设置桶访问权限为私有读写,默认也是私有读写
            request.setAcl(AccessControlList.REST_CANNED_PRIVATE);
            // 设置桶的存储类别为标准存储
            request.setBucketStorageClass(StorageClassEnum.STANDARD);
            // 设置桶区域位置(以区域为中国-香港为例),location 需要与 endpoint的位置信息一致
            request.setLocation(exampleLocation);
            // 指定创建多AZ桶,如果不设置,默认创建单AZ桶
            request.setAvailableZone(AvailableZoneEnum.MULTI_AZ);
            // 创建桶
            ObsBucket bucket = obsClient.createBucket(request);
            // 创建桶成功
            System.out.println("CreateBucket successfully");
            System.out.println("RequestId:"+bucket.getRequestId());


        } catch (ObsException e) {
            System.out.println("CreateBucket failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code: " + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message: " + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
        } catch (Exception e) {
            System.out.println("CreateBucket failed");
            // 其他异常信息打印
            e.printStackTrace();

        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from obs import CreateBucketHeader, HeadPermission
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 创建桶的附加头域,桶的访问控制策略是私有桶,存储类型是标准存储,多AZ方式存储
    header = CreateBucketHeader(aclControl=HeadPermission.PRIVATE, storageClass="STANDARD", availableZone="3az")
    # 指定存储桶所在区域,此处以“ap-southeast-1”为例,必须跟传入的Endpoint中Region保持一致。
    location = "ap-southeast-1"
    # 指定存储桶所在区域,必须跟传入的endpoint所在的region保持一致
    location = "region"
    bucketName = "examplebucket"
    # 创建桶
    resp = obsClient.createBucket(bucketName, header, location)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Create Bucket Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Create Bucket Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Create Bucket Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.CreateBucketInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定存储桶所在区域,此处以“ap-southeast-1”为例,必须跟传入的Endpoint中Region保持一致。
    input.Location = "ap-southeast-1"
    // 指定存储桶所在区域,必须跟传入的Endpoint中Region保持一致。
    input.Location = "region"
    // 指定存储桶的权限控制策略,此处以obs.AclPrivate为例。
    input.ACL = obs.AclPrivate
    // 指定存储桶的存储类型,此处以obs.StorageClassWarm为例。如果未指定该参数,则创建的桶为标准存储类型。
    input.StorageClass = obs.StorageClassWarm
    // 指定存储桶的AZ类型,此处以“3AZ”为例。不携带时默认为单AZ,如果对应region不支持多AZ存储,则该桶的存储类型仍为单AZ。
    input.AvailableZone = "3az"
    // 创建桶
    output, err := obsClient.CreateBucket(input)
    if err == nil {
        fmt.Printf("Create bucket:%s successful!\n", input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        return
    }
    fmt.Printf("Create bucket:%s fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

步骤二:上传对象

以下示例展示了上传本地文件localfile到examplebucket桶中,并将对象名设置为objectname。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;
import java.io.File;
public class PutObject004 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 文件上传
            PutObjectRequest request = new PutObjectRequest();
            // 上传文件到examplebucket桶中
            request.setBucketName("examplebucket");
            // 指定上传到examplebucket桶中的文件名称
            request.setObjectKey("objectname");
            // 指定本地待上传文件的路径
            request.setFile(new File("localfile"));
            obsClient.putObject(request);
            System.out.println("putObject successfully");
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from obs import ObsClient
from obs import PutObjectHeader
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
# 运行本代码示例之前,请确保已设置环境变量AccessKeyID和SecretAccessKey。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 上传对象的附加头域
    headers = PutObjectHeader()
    # 上传到名为examplebucket的桶中
    bucketName = "examplebucket"
    # 对象名,即上传后的文件名
    objectKey = "objectname"
    # 待上传文件/文件夹的本地完整路径,如aa/bb.txt,或aa/
    file_path = 'localfile'
    # 文件上传
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        print('etag:', resp.body.etag)
        print('versionId:', resp.body.versionId)
        print('storageClass:', resp.body.storageClass)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put File Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutFileInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定上传对象,此处以 objectname 为例。
    input.Key = "objectname"
    // 指定本地文件,此处以localfile为例
    input.SourceFile = "localfile"
    // 文件上传
    output, err := obsClient.PutFile(input)
    if err == nil {
        fmt.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s\n",
            output.StorageClass, output.ETag)
        return
    }
    fmt.Printf("Put file(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;
import java.io.File;
public class PutObject004 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 文件上传
            PutObjectRequest request = new PutObjectRequest();
            // 上传文件到examplebucket桶中
            request.setBucketName("examplebucket");
            // 指定上传到examplebucket桶中的文件名称
            request.setObjectKey("objectname");
            // 指定本地待上传文件的路径
            request.setFile(new File("localfile"));
            obsClient.putObject(request);
            System.out.println("putObject successfully");
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from obs import ObsClient
from obs import PutObjectHeader
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
# 运行本代码示例之前,请确保已设置环境变量AccessKeyID和SecretAccessKey。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 上传对象的附加头域
    headers = PutObjectHeader()
    # 上传到名为examplebucket的桶中
    bucketName = "examplebucket"
    # 对象名,即上传后的文件名
    objectKey = "objectname"
    # 待上传文件/文件夹的本地完整路径,如aa/bb.txt,或aa/
    file_path = 'localfile'
    # 文件上传
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        print('etag:', resp.body.etag)
        print('versionId:', resp.body.versionId)
        print('storageClass:', resp.body.storageClass)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put File Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutFileInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定上传对象,此处以 objectname 为例。
    input.Key = "objectname"
    // 指定本地文件,此处以localfile为例
    input.SourceFile = "localfile"
    // 文件上传
    output, err := obsClient.PutFile(input)
    if err == nil {
        fmt.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s\n",
            output.StorageClass, output.ETag)
        return
    }
    fmt.Printf("Put file(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

步骤三:下载对象

本示例用于下载examplebucket桶中的objectname对象。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObsObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class GetObject001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。查看桶所在的endpoint请参见:https://support.huaweicloud.com/intl/zh-cn/usermanual-obs/obs_03_0312.html
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 流式下载
            ObsObject obsObject = obsClient.getObject("examplebucket", "objectname");
            // 读取对象内容
            System.out.println("Object content:");
            InputStream input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len = input.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            System.out.println("getObjectContent successfully");
            System.out.println(new String(bos.toByteArray()));
            bos.close();
            input.close();
        } catch (ObsException e) {
            System.out.println("getObjectContent failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("getObjectContent failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from obs import GetObjectRequest
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 下载对象的附加请求参数
    getObjectRequest = GetObjectRequest()
    # 获取对象时重写响应中的Content-Type头。
    getObjectRequest.content_type = 'text/plain'
    bucketName="examplebucket"
    objectKey="objectname"
    #流式下载
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, getObjectRequest=getObjectRequest, loadStreamInMemory=False)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # 读取对象内容
        while True:
            chunk = resp.body.response.read(65536)
            if not chunk:
                break
            print(chunk)
        resp.body.response.close()
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Object Failed')  
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.GetObjectInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定下载对象,此处以 objectname 为例。
    input.Key = "objectname"
    // 流式下载对象
    output, err := obsClient.GetObject(input)
    if err == nil {
        // output.Body 在使用完毕后必须关闭,否则会造成连接泄漏。
        defer output.Body.Close()
        fmt.Printf("Get object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
            output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
        // 读取对象内容
        p := make([]byte, 1024)
        var readErr error
        var readCount int
        for {
            readCount, readErr = output.Body.Read(p)
            if readCount > 0 {
                fmt.Printf("%s", p[:readCount])
            }
            if readErr != nil {
                break
            }
        }
        return
    }
    fmt.Printf("List objects under the bucket(%s) fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObsObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class GetObject001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。查看桶所在的endpoint请参见:https://support.huaweicloud.com/intl/zh-cn/usermanual-obs/obs_03_0312.html
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 流式下载
            ObsObject obsObject = obsClient.getObject("examplebucket", "objectname");
            // 读取对象内容
            System.out.println("Object content:");
            InputStream input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len = input.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            System.out.println("getObjectContent successfully");
            System.out.println(new String(bos.toByteArray()));
            bos.close();
            input.close();
        } catch (ObsException e) {
            System.out.println("getObjectContent failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("getObjectContent failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from obs import GetObjectRequest
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 下载对象的附加请求参数
    getObjectRequest = GetObjectRequest()
    # 获取对象时重写响应中的Content-Type头。
    getObjectRequest.content_type = 'text/plain'
    bucketName="examplebucket"
    objectKey="objectname"
    #流式下载
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, getObjectRequest=getObjectRequest, loadStreamInMemory=False)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # 读取对象内容
        while True:
            chunk = resp.body.response.read(65536)
            if not chunk:
                break
            print(chunk)
        resp.body.response.close()
    else:
        print('Get Object Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Object Failed')  
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"
    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.GetObjectInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 指定下载对象,此处以 objectname 为例。
    input.Key = "objectname"
    // 流式下载对象
    output, err := obsClient.GetObject(input)
    if err == nil {
        // output.Body 在使用完毕后必须关闭,否则会造成连接泄漏。
        defer output.Body.Close()
        fmt.Printf("Get object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
            output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
        // 读取对象内容
        p := make([]byte, 1024)
        var readErr error
        var readCount int
        for {
            readCount, readErr = output.Body.Read(p)
            if readCount > 0 {
                fmt.Printf("%s", p[:readCount])
            }
            if readErr != nil {
                break
            }
        }
        return
    }
    fmt.Printf("List objects under the bucket(%s) fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

步骤四:简单列举对象

以下代码展示如何简单列举examplebucket桶下的对象。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObjectListing;
import com.obs.services.model.ObsObject;
public class ListObjects001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 简单列举
            ObjectListing result = obsClient.listObjects("examplebucket");
            for (ObsObject obsObject : result.getObjects()) {
                System.out.println("listObjects successfully");
                System.out.println("ObjectKey:" + obsObject.getObjectKey());
                System.out.println("Owner:" + obsObject.getOwner());
            }
        } catch (ObsException e) {
            System.out.println("listObjects failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listObjects failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = "examplebucket"
    # 指定列举对象的前缀
    prefix = 'test/'
    # 指定单次列举对象个数为100
    max_keys = 100
    # 列举桶内对象
    resp = obsClient.listObjects(bucketName, prefix, max_keys=max_keys, encoding_type='url')

    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('List Objects Succeeded')
        print('requestId:', resp.requestId)
        print('name:', resp.body.name)
        print('prefix:', resp.body.prefix)
        print('max_keys:', resp.body.max_keys)
        print('is_truncated:', resp.body.is_truncated)
        index = 1
        for content in resp.body.contents:
            print('object [' + str(index) + ']')
            print('key:', content.key)
            print('lastModified:', content.lastModified)
            print('etag:', content.etag)
            print('size:', content.size)
            print('storageClass:', content.storageClass)
            print('owner_id:', content.owner.owner_id)
            print('owner_name:', content.owner.owner_name)
            index += 1
    else:
        print('List Objects Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('List Objects Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")

    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"

    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.ListObjectsInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 列举桶内对象
    output, err := obsClient.ListObjects(input)
    if err == nil {
        fmt.Printf("List objects under the bucket(%s) successful!\n", input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        for index, val := range output.Contents {
            fmt.Printf("Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d\n",
                index, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size)
        }
        return
    }
    fmt.Printf("List objects under the bucket(%s) fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObjectListing;
import com.obs.services.model.ObsObject;
public class ListObjects001 {
    public static void main(String[] args) {
        // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
        // 您可以登录访问管理控制台获取访问密钥AK/SK
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // endpoint填写桶所在的endpoint, 此处以中国-香港为例,其他地区请按实际情况填写。
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // endpoint填写桶所在区域的endpoint。
        String endPoint = "https://your-endpoint";
        
        // 创建ObsClient实例
        // 使用永久AK/SK初始化客户端
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 简单列举
            ObjectListing result = obsClient.listObjects("examplebucket");
            for (ObsObject obsObject : result.getObjects()) {
                System.out.println("listObjects successfully");
                System.out.println("ObjectKey:" + obsObject.getObjectKey());
                System.out.println("Owner:" + obsObject.getOwner());
            }
        } catch (ObsException e) {
            System.out.println("listObjects failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listObjects failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# server填写桶所在区域的endpoint。
server = "https://your-endpoint"

# 创建obsClient实例
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = "examplebucket"
    # 指定列举对象的前缀
    prefix = 'test/'
    # 指定单次列举对象个数为100
    max_keys = 100
    # 列举桶内对象
    resp = obsClient.listObjects(bucketName, prefix, max_keys=max_keys, encoding_type='url')

    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('List Objects Succeeded')
        print('requestId:', resp.requestId)
        print('name:', resp.body.name)
        print('prefix:', resp.body.prefix)
        print('max_keys:', resp.body.max_keys)
        print('is_truncated:', resp.body.is_truncated)
        index = 1
        for content in resp.body.contents:
            print('object [' + str(index) + ']')
            print('key:', content.key)
            print('lastModified:', content.lastModified)
            print('etag:', content.etag)
            print('size:', content.size)
            print('storageClass:', content.storageClass)
            print('owner_id:', content.owner.owner_id)
            print('owner_name:', content.owner.owner_name)
            index += 1
    else:
        print('List Objects Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('List Objects Failed')
    print(traceback.format_exc())
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
    "fmt"
    "os"
    "obs-sdk-go/obs"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")

    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // endpoint填写桶所在区域的endpoint。
    endPoint := "https://your-endpoint"

    // 创建obsClient实例
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.ListObjectsInput{}
    // 指定存储桶名称
    input.Bucket = "examplebucket"
    // 列举桶内对象
    output, err := obsClient.ListObjects(input)
    if err == nil {
        fmt.Printf("List objects under the bucket(%s) successful!\n", input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        for index, val := range output.Contents {
            fmt.Printf("Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d\n",
                index, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size)
        }
        return
    }
    fmt.Printf("List objects under the bucket(%s) fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

相关信息

当您完成创建桶、上传对象、下载对象等基本操作后,您还可以结合业务需求使用以下Java SDK的高阶功能。

  • 生命周期:通过为桶配置生命周期规则,可以实现定时转换对象存储类别或定时删除对象。
  • 桶ACL权限:Java SDK提供桶ACL访问权限方式,桶的所有者可以通过编写桶ACL,实现对桶更精细化的权限控制。
  • 桶策略:Java SDK提供桶策略访问权限方式,桶的所有者可以通过编写桶策略,实现对桶更精细化的权限控制。
  • 静态网站托管:您可以将静态网站文件上传至OBS的桶中,并对这些文件赋予匿名用户可读权限,然后将该桶配置成静态网站托管模式,实现使用桶域名访问该网站。
  • 多版本控制:为桶开启多版本控制后,可以在桶中保留多个版本的对象,方便检索和还原各个版本,在意外操作或应用程序故障时帮助快速恢复数据。
  • 服务端加密:通过服务端加密功能,对上传至OBS桶中的数据进行加密保护。
  • 跨域资源共享(CORS):通过配置CORS规则,可以实现跨域名访问OBS。

我们使用cookie来确保您的高速浏览体验。继续浏览本站,即表示您同意我们使用cookie。 详情

文档反馈

文档反馈

意见反馈

0/500

标记内容

同时提交标记内容