Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Using OBS SDKs

Updated on 2024-09-29 GMT+08:00

OBS software development kits (SDKs) encapsulate the REST API provided by OBS to simplify development. You can call API functions provided by OBS SDKs to use OBS.

The following describes how to use basic OBS functions with SDK for Java, SDK for Python, and SDK for Go, including creating a bucket, as well as uploading, downloading, and listing objects.

Preparations

Before using the SDK for Java, you must create a HUAWEI ID, complete real-name authentication, and top up your account. Then, you need to obtain the access keys, set up a development environment, and install the SDK for Java.

  1. Sign up for a HUAWEI ID and complete real-name authentication.

    If you already have a HUAWEI ID, skip this step. Otherwise, do as follows:

    1. Sign up for a HUAWEI ID and enable Huawei Cloud services.
    2. Complete real-name authentication by referring to Individual Real-Name Authentication or .

  2. Top up your account by referring to Topping Up an Account.

    Make sure your account balance is sufficient, so that you can properly use OBS and other related resources.

  3. Obtain the access keys by referring to Access Keys.
  4. Set up a development environment by referring to Setting Up a Development Environment.
  5. Download and install the SDK for Java by referring to SDK Download and Installation (SDK for Java).

Creating a Bucket

The following example shows how to create a private bucket (examplebucket as an example) in the CN-Hong Kong (ap-southeast-1) region. The storage class is set to Standard. The redundancy is set to multi-AZ storage.

 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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");

        // Enter the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where you want to create the bucket.
        String endPoint = "https://your-endpoint";

        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        
        try {
            CreateBucketRequest request = new CreateBucketRequest();
            //Specify a bucket name.
            String exampleBucket = "examplebucket";
            //Specify a bucket location.
            String exampleLocation = "ap-southeast-1";
            request.setBucketName(exampleBucket);
            // Set the bucket ACL to private (the default value).
            request.setAcl(AccessControlList.REST_CANNED_PRIVATE);
            // Set the bucket storage class to Standard.
            request.setBucketStorageClass(StorageClassEnum.STANDARD);
            // Specify the bucket location (CN-Hong Kong as an example). The location must match the endpoint.
            request.setLocation(exampleLocation);
            // Specify the multi-AZ redundancy for the bucket. If this field is not configured, a single-AZ bucket will be created.
            request.setAvailableZone(AvailableZoneEnum.MULTI_AZ);
            // Create the bucket.
            ObsBucket bucket = obsClient.createBucket(request);
            // The bucket is created.
            System.out.println("CreateBucket successfully");
            System.out.println("RequestId:"+bucket.getRequestId());


        } catch (ObsException e) {
            System.out.println("CreateBucket failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code: " + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message: " + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
        } catch (Exception e) {
            System.out.println("CreateBucket failed");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where you want to create the bucket.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional headers to create a private bucket that is in the Standard storage class and supports multi-AZ storage.
    header = CreateBucketHeader(aclControl=HeadPermission.PRIVATE, storageClass="STANDARD", availableZone="3az")
    # Specify the region where you want to create the bucket. ap-southeast-1 is used here as an example. The region must be the one you specified in the endpoint.
    location = "ap-southeast-1"
    # Specify the region where you want to create the bucket. The region must be the one you specified in the endpoint.
    location = "region"
    bucketName = "examplebucket"
    # Create the bucket.
    resp = obsClient.createBucket(bucketName, header, location)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where you want to create the bucket.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.CreateBucketInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the region where you want to create the bucket. ap-southeast-1 is used here as an example. The region must be the one you specified in the endpoint.
    input.Location = "ap-southeast-1"
    // Specify the region where you want to create the bucket. The region must be the one you specified in the endpoint.
    input.Location = "region"
    // Set the bucket ACL to obs.AclPrivate (an example).
    input.ACL = obs.AclPrivate
    // Specify the storage class of the bucket. obs.StorageClassWarm is used here as an example. If this field is not specified, a Standard bucket will be created.
    input.StorageClass = obs.StorageClassWarm
    // Specify the AZ redundancy type. 3-AZ redundancy is used here as an example. If this field is not specified or the region does not support multi-AZ storage, single-AZ redundancy will be applied.
    input.AvailableZone = "3az"
    // Create the bucket.
    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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");

        // Enter the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where you want to create the bucket.
        String endPoint = "https://your-endpoint";

        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        
        try {
            CreateBucketRequest request = new CreateBucketRequest();
            //Specify a bucket name.
            String exampleBucket = "examplebucket";
            //Specify a bucket location.
            String exampleLocation = "ap-southeast-1";
            request.setBucketName(exampleBucket);
            // Set the bucket ACL to private (the default value).
            request.setAcl(AccessControlList.REST_CANNED_PRIVATE);
            // Set the bucket storage class to Standard.
            request.setBucketStorageClass(StorageClassEnum.STANDARD);
            // Specify the bucket location (CN-Hong Kong as an example). The location must match the endpoint.
            request.setLocation(exampleLocation);
            // Specify the multi-AZ redundancy for the bucket. If this field is not configured, a single-AZ bucket will be created.
            request.setAvailableZone(AvailableZoneEnum.MULTI_AZ);
            // Create the bucket.
            ObsBucket bucket = obsClient.createBucket(request);
            // The bucket is created.
            System.out.println("CreateBucket successfully");
            System.out.println("RequestId:"+bucket.getRequestId());


        } catch (ObsException e) {
            System.out.println("CreateBucket failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code: " + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message: " + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
        } catch (Exception e) {
            System.out.println("CreateBucket failed");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where you want to create the bucket.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional headers to create a private bucket that is in the Standard storage class and supports multi-AZ storage.
    header = CreateBucketHeader(aclControl=HeadPermission.PRIVATE, storageClass="STANDARD", availableZone="3az")
    # Specify the region where you want to create the bucket. ap-southeast-1 is used here as an example. The region must be the one you specified in the endpoint.
    location = "ap-southeast-1"
    # Specify the region where you want to create the bucket. The region must be the one you specified in the endpoint.
    location = "region"
    bucketName = "examplebucket"
    # Create the bucket.
    resp = obsClient.createBucket(bucketName, header, location)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where you want to create the bucket. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where you want to create the bucket.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.CreateBucketInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the region where you want to create the bucket. ap-southeast-1 is used here as an example. The region must be the one you specified in the endpoint.
    input.Location = "ap-southeast-1"
    // Specify the region where you want to create the bucket. The region must be the one you specified in the endpoint.
    input.Location = "region"
    // Set the bucket ACL to obs.AclPrivate (an example).
    input.ACL = obs.AclPrivate
    // Specify the storage class of the bucket. obs.StorageClassWarm is used here as an example. If this field is not specified, a Standard bucket will be created.
    input.StorageClass = obs.StorageClassWarm
    // Specify the AZ redundancy type. 3-AZ redundancy is used here as an example. If this field is not specified or the region does not support multi-AZ storage, single-AZ redundancy will be applied.
    input.AvailableZone = "3az"
    // Create the bucket.
    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)
    }
}

Uploading an Object

The following example shows how to upload the localfile file to bucket examplebucket and set the object name to 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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // Upload a file.
            PutObjectRequest request = new PutObjectRequest();
            // Set the bucket name to examplebucket.
            request.setBucketName("examplebucket");
            // Specify the name of the file to be uploaded to the examplebucket bucket.
            request.setObjectKey("objectname");
            // Specify the path of the local file to be uploaded.
            request.setFile(new File("localfile"));
            obsClient.putObject(request);
            System.out.println("putObject successfully");
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
# Before running this sample code, ensure that the environment variables AccessKeyID and SecretAccessKey have been configured.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional headers for object upload.
    headers = PutObjectHeader()
    # Specify the bucket name to examplebucket.
    bucketName = "examplebucket"
    # Specify the object name (the name after the file is uploaded).
    objectKey = "objectname"
    # Specify the local full path of the file or folder to be uploaded, for example, aa/bb.txt or aa/.
    file_path = 'localfile'
    #  Upload the file.
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutFileInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Set the object name to objectname (an example).
    input.Key = "objectname"
    // Specify the local file (localfile as an example).
    input.SourceFile = "localfile"
    // Upload the file.
    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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // Upload a file.
            PutObjectRequest request = new PutObjectRequest();
            // Set the bucket name to examplebucket.
            request.setBucketName("examplebucket");
            // Specify the name of the file to be uploaded to the examplebucket bucket.
            request.setObjectKey("objectname");
            // Specify the path of the local file to be uploaded.
            request.setFile(new File("localfile"));
            obsClient.putObject(request);
            System.out.println("putObject successfully");
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
# Before running this sample code, ensure that the environment variables AccessKeyID and SecretAccessKey have been configured.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional headers for object upload.
    headers = PutObjectHeader()
    # Specify the bucket name to examplebucket.
    bucketName = "examplebucket"
    # Specify the object name (the name after the file is uploaded).
    objectKey = "objectname"
    # Specify the local full path of the file or folder to be uploaded, for example, aa/bb.txt or aa/.
    file_path = 'localfile'
    #  Upload the file.
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutFileInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Set the object name to objectname (an example).
    input.Key = "objectname"
    // Specify the local file (localfile as an example).
    input.SourceFile = "localfile"
    // Upload the file.
    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)
    }
}

Downloading an Object

The following example shows how to download the objectname object from bucket 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
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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use. To check the endpoint, see https://support.huaweicloud.com/intl/en-us/usermanual-obs/obs_03_0312.html.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // Download the object using streaming.
            ObsObject obsObject = obsClient.getObject("examplebucket", "objectname");
            // Read the object content.
            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");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional parameters for object download.
    getObjectRequest = GetObjectRequest()
    # Rewrite the Content-Type header in the response.
    getObjectRequest.content_type = 'text/plain'
    bucketName="examplebucket"
    objectKey="objectname"
    #Download the object using streaming.
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, getObjectRequest=getObjectRequest, loadStreamInMemory=False)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # Read the object content.
        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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.GetObjectInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the object (objectnameas an example) to download.
    input.Key = "objectname"
    // Download the object using streaming.
    output, err := obsClient.GetObject(input)
    if err == nil {
        // The output.Body must be closed after use to prevent connection leakage.
        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)
        // Read the object content.
        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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use. To check the endpoint, see https://support.huaweicloud.com/intl/en-us/usermanual-obs/obs_03_0312.html.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // Download the object using streaming.
            ObsObject obsObject = obsClient.getObject("examplebucket", "objectname");
            // Read the object content.
            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");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify the additional parameters for object download.
    getObjectRequest = GetObjectRequest()
    # Rewrite the Content-Type header in the response.
    getObjectRequest.content_type = 'text/plain'
    bucketName="examplebucket"
    objectKey="objectname"
    #Download the object using streaming.
    resp = obsClient.getObject(bucketName=bucketName,objectKey=objectKey, getObjectRequest=getObjectRequest, loadStreamInMemory=False)
    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    if resp.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp.requestId)
        # Read the object content.
        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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"
    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.GetObjectInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the object (objectnameas an example) to download.
    input.Key = "objectname"
    // Download the object using streaming.
    output, err := obsClient.GetObject(input)
    if err == nil {
        // The output.Body must be closed after use to prevent connection leakage.
        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)
        // Read the object content.
        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)
    }
}

Listing Objects

The following example shows how to list objects in bucket 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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // List objects.
            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");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = "examplebucket"
    # Specify an object prefix.
    prefix = 'test/'
    # Specify the maximum number (100 as an example) of objects to be listed at a time.
    max_keys = 100
    # List objects in the bucket.
    resp = obsClient.listObjects(bucketName, prefix, max_keys=max_keys, encoding_type='url')

    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")

    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"

    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.ListObjectsInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // List objects in the bucket.
    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) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Enter the endpoint for the region where the bucket is created.
        String endPoint = "https://your-endpoint";
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the ObsClient.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // List objects.
            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");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error message.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request 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");
            // Print other error information.
            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

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# Set server to the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# Set server to the endpoint for the region where the bucket is created.
server = "https://your-endpoint"

# Create an ObsClient instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = "examplebucket"
    # Specify an object prefix.
    prefix = 'test/'
    # Specify the maximum number (100 as an example) of objects to be listed at a time.
    max_keys = 100
    # List objects in the bucket.
    resp = obsClient.listObjects(bucketName, prefix, max_keys=max_keys, encoding_type='url')

    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    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() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")

    // Enter the endpoint for the region where the bucket is created. The CN-Hong Kong (ap-southeast-1) region is used here as an example. Replace it with the one in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Enter the endpoint for the region where the bucket is created.
    endPoint := "https://your-endpoint"

    // Create an ObsClient instance.
    obsClient, err := obs.New(ak, sk, endPoint)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.ListObjectsInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // List objects in the bucket.
    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)
    }
}

Related Information

In addition to the operations mentioned above, the following advanced functions of OBS for Java SDK are available for you to use.

  • Lifecycle management: You can configure lifecycle rules to periodically transition objects between storage classes or delete objects.
  • Bucket ACL: You (the bucket owner) can write the bucket ACL using the SDK for Java to implement fine-grained access control.
  • Bucket policies: You (the bucket owner) can write bucket policies using the SDK for Java to implement fine-grained access control.
  • Static website hosting: You can upload a static website file to an OBS bucket, grant anonymous users the read permission for this file, and configure static website hosting for the bucket, so that you can use the bucket domain name to access the hosted static website file.
  • Versioning: You can enable versioning for a bucket to keep multiple versions of an object in the same bucket. This way, you can easily retrieve and restore each object version and recover data from unintended actions or application failures.
  • Server-side encryption: You can use server-side encryption to encrypt data uploaded to OBS buckets.
  • Cross-origin resource sharing (CORS): You can configure a CORS rule to enable cross-domain quests for OBS.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback