百度智能云

All Product Document

          Object Storage

          Initialization

          Getting Started

          1.Initialize BosClient.

          BosClient is a client that interacts with BOS services. BOS operations of BOS Android SDK are all completed through BosClient.

          Sample code:

          BosClientConfiguration config = new BosClientConfiguration();
          config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));   //Your AK/SK
          config.setEndpoint(<EndPoint>);    //Introduce into domain name of the region where the bucket is
          BosClient client = new BosClient(config);

          2.Create bucket.

          Bucket is a namespace on BOS. It is equivalent to a container of data and can store several data entities (objects). Before uploading data, you must create a bucket.

          Sample code:

          BosClient client = new BosClient(config);    //Create the instance of BOSClient. 
              client.createBucket(<BucketName>);     //Create a bucket and specify the name of the Bucket 

          3.Upload object.

          object is the most basic data unit in BOS. You can understand object as a file. OS provides you with four ways to upload an object: File upload, data stream upload, binary string upload and string upload.

          Sample code:

          // Access specified files
          File file = new File(<FilePath>);     //Designate file path. 
          
          // Upload object as file
          PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
          
          // Access data stream
          InputStream inputStream = new FileInputStream(<FilePath>);
          
          // Upload object as the data stream
          PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream);
          
          // Upload object as the binary string
          PutObjectResponse putObjectResponseFromByte = client.putObject(<BucketName>, <ObjectKey>, <byte>);
          
          // Upload object as the character string
          PutObjectResponse putObjectResponseFromString = client.putObject(<BucketName>, <ObjectKey>, <string>);
          
          // Print ETag
          System.out.println(putObjectFromFileResponse.getETag());

          4.View the objects list under bucket.

          After completing uploads, you can refer to the following code to view all objects under bucket.

          Sample code:

          // Access all Object information of specified Bucket
          ListObjectsResponse listing = client.listObjects(<BucketName>);
          
          // Traverse all Objects
          for (BosObjectSummary objectSummary : listing.getContents()) {
            System.out.println("ObjectKey: " + objectSummary.getKey());
            }

          5.Get the specified object.

          You can refer to the following code to get one or more objects.

          Sample code:

           // Get object and return BosObject 
           BosObject object = client.getObject(<BucketName>,<ObjectKey>); 
              
           // Get ObjectMeta 
           ObjectMetadata meta = object.getObjectMetadata(); 
              
           // Get the input stream of Object. 
           InputStream ObjectContent = object.getObjectContent(); 
              
           // Process Object 
           ...
              
           // Close stream 
            objectContent.close(); 

          Complete Example

          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;
          
          import android.os.Bundle;
          
          import com.baidubce.BceClientException;
          import com.baidubce.BceServiceException;
          import com.baidubce.auth.DefaultBceCredentials;
          import com.baidubce.development.AppSettings;
          import com.baidubce.development.BaseActivity;
          import com.baidubce.development.R;
          import com.baidubce.services.bos.BosClient;
          import com.baidubce.services.bos.BosClientConfiguration;
          import com.baidubce.services.bos.model.BosObject;
          import com.baidubce.services.bos.model.BosObjectSummary;
          import com.baidubce.services.bos.model.CreateBucketResponse;
          import com.baidubce.services.bos.model.ListObjectsResponse;
          import com.baidubce.services.bos.model.ObjectMetadata;
          import com.baidubce.services.bos.model.PutObjectResponse;
          import com.baidubce.util.BLog;
          
          public class ExampleActivity extends BaseActivity {
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  //Open bossdk runtime log
                  BLog.enableLog();
          
                  BosClientConfiguration config = new BosClientConfiguration();
                  config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>)); 
                  config.setEndpoint(<EndPoint>); //Region where bucket is located
                  final BosClient client = new BosClient(config);
          
                  new Thread(new Runnable() {
          
                      @Override
                      public void run() {
          
                          try {
                              //Create Bucket
                              CreateBucketResponse response = client.createBucket(<BucketName>); //Create a Bucket and specify the name of the Bucket 
                              System.out.println(response.getLocation());
                              System.out.println(response.getName());
          
                              //Upload Object
                              File file = new File(<Path>);//Upload the directory of files
                              PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
                              System.out.println(putObjectFromFileResponse.getETag());
          
                              //View Object
                              ListObjectsResponse list = client.listObjects(<BucketName>);
                              for (BosObjectSummary objectSummary : list.getContents()) {
                                  System.out.println("ObjectKey: " + objectSummary.getKey());
                              }
          
                              // Get Object
                              BosObject object = client.getObject(<BucketName>, <ObjectKey>);
                              // Get ObjectMeta
                              ObjectMetadata meta = object.getObjectMetadata();
                              // Get the input stream of Object
                              InputStream objectContent = object.getObjectContent();
                              // Process Object
                              FileOutputStream fos=new FileOutputStream(<Path>);//Directory/filename for downloading files
                              byte[] buffer=new byte[2048];
                              int count=0;
                              while ((count=objectContent.read(buffer))>=0) {
                                  fos.write(buffer,0,count);
                              }
                              
                              // Close stream
                              objectContent.close();
                              fos.close();
                              System.out.println(meta.getETag());
                              System.out.println(meta.getContentLength());
          
                          }catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          }
          
          
          
                      } 
                  }).start(); 
          
              } 
          } 

          Create BOSClient

          BosClient is the client of BOS service, providing methods for developers to interact with BOS service. Before using SDK to initiate a request to BOS, you need to initialize a BosClient instance and make some necessary settings to it.

          • Basic procedure

            1.Determine the EndPoint. EndPoint refers to the domain name address of BOS service in various regions, for example, Beijing domain name is bj.bcebos.com. 2.Create a BosClientConfiguration instance. 3.Use setCredentials to introduce your AK/SK into BosClientConfiguration. 4.Introduce the configured BosClientConfiguration into BosClient.

          • Sample Code

            BosClientConfiguration config = new BosClientConfiguration();

            config.setCredentials(new DefaultBceCredentials(, )); //Your AK/SK config.setEndpoint(); //Introduce into domain name of the region where the bucket is BosClient client = new BosClient(config);

            Note: The EndPoint parameter can only be defined with the specified domain name containing the region. Baidu AI Cloud currently has opened access to multi-region support, please refer to Region Selection Description.

            Currently, it supports "North China-Beijing", "South China-Guangzhou" and "East China-Suzhou". Beijing: http://bj.bcebos.com; Guangzhou: http://gz.bcebos.com; Suzhou: http://su.bcebos.com.

            Direct login using AK/SK means that your account information may be exposed to a third party. For security reasons, we do not recommend you to access BOS in this way. If you have to use this method, be sure to protect your account assets.

          Create BosClient with STS Verification

          Android SDK is mainly used for scenarios developed by the mobile terminal. For authentication of the mobile terminal, if you directly disclose your AK/SK to the mobile terminal, it is bound to bring security risks to your account. Therefore, it is recommended that you use STS for authentication of the mobile terminal. Please refer to Temporary Authorized Access for detailed information on STS.

          Using STS mode requires you to first create a BosClient with STS to execute when calling API. Currently, the STS of BOS only supports API calls of the following methods:

          • Deleteobject
          • Putobject
          • ListParts
          • Getobject
          • DoesBucketExist
          • CompleteMultipartUpload
          • AbortMultipartUpload
          • InitiateMultipartUpload
          • UploadPart

          Sample code:

          BosClientConfiguration config = new BosClientConfiguration(); // Initialize a BosClient with STS verification. config.setCredentials(new DefaultBceSessionCredentials(<AccessKeyID>,<SecretAccessKey>,<Token>); //Temporary AK/SK and Token returned by STS BosClient client = new BosClient(config);

          Note: In the following code examples, the original AK/SK is used to create a BosClient. If you need to use a BosClient with STS authentication, follow the above method when creating a BosClient.

          Configure HTTPS to Access BOS

          BOS supports the HTTPS, and you can use HTTPS to access BOS services in the BOS Android SDK in the following two ways:

          • Indicate https in endpoint.

            String endpoint = "https://bj.bcebos.com";
            String ak = "ak";
            String sk = "sk";
            BosClientConfiguration config = new BosClientConfigration();
            config.setEndpoint(endpoint);  
            config.setCredentials(new DefaultBceCredentials(ak, sk));
            BosClient client = new BosClient(config);
          • Set the https protocol by calling the setProtocol method:

            String endpoint = "bj.bcebos.com"; // endpoint中不包含protocol
            String ak = "ak";
            String sk = "sk";
            BosClientConfiguration config = new BosClientConfigration();
            config.setEndpoint(endpoint);  
            config.setCredentials(new DefaultBceCredentials(ak, sk));
            config.setProtocol(Protocol.HTTPS); // If protocol is not indicated, http is used
            BosClient client = new BosClient(config);

            Note: If protocol is indicated in endpoint, the entry in endpoint takes effect, and a separate call to setProtocol () does not work.

              String endpoint = "http://bj.bcebos.com";
              String ak = "ak";
              String sk = "sk";
              BosClientConfiguration config = new BosClientConfigration();
              config.setEndpoint(endpoint); 
              config.setCredentials(new DefaultBceCredentials(ak, sk));
              config.setProtocol(Protocol.HTTPS); // As indicated in endpoint, this is an invalid operation, as is http
              BosClient client = new BosClient(config);

          Configure BosClient

          If you need to configure some detailed parameters of the BosClient, introduce into the BosClientConfiguration object when constructing the BosClient. BosClientConfiguration is the configuration class of BOS service. You can set basic network parameters through BosClientConfiguration.

          Set Network Parameters

          You can use BosClientConfiguration to set basic network parameters.

          • Sample Code

              BosClientConfiguration config = new BosClientConfiguration(); 
                
              // Set the maximum number of HTTP connections to 10.
              config.setMaxConnections(10); 
                
              // Set TCP connection timeout to 5,000 milliseconds 
              config.setConnectionTimeout(5000); 
                
              // Set the timeout for socket data transmission to 2,000 milliseconds 
              config.setSocketTimeout(2000); 
          • Parameter description

            All parameters that can be specified through BosClientConfiguration are shown in the following table:

            Parameter Description
            UserAgent User agent, referring to the HTTP User-Agent header
            Protocol Connection protocol type, default-value HTTP protocol
            LocalAddress Local address
            ConnectionTimeoutInMillis Timeout for establishing a connection (unit: ms), with default value of 30,000.
            SocketTimeoutInMillis Timeout for transmitting data over open connections (unit: ms), with default value of 30,000.
            MaxConnections Maximum number of HTTP connections allowed to open, with default value of 5.
            RetryPolicy Connection retry policy
            SocketBufferSizeInBytes Socket buffer size
            StreamBufferSize Stream file buffer size
          Previous
          SDK Installation
          Next
          Bucket Management