Initialization
Quick Start
-
Initialize a BosClient using STS authentication.
A BosClient is the interface to the BOS service. All BOS operations in the BOS Android SDK are executed through the BosClient.
Example code:
Java1BosClientConfiguration config = new BosClientConfiguration(); ////Initialize a BosClient with STS authentication 2 config.setCredentials(new DefaultBceSessionCredentials(<AccessKeyID>, <SecretAccessKey>, <Token>); //Temporary AK/SK and Token returned by STS 3 config.setEndpoint(<EndPoint>); //Pass in the domain name of the region where the bucket is located 4BosClient client = new BosClient(config); -
Create a bucket.
A bucket is a namespace in BOS that serves as a container for data and can hold multiple data entities (objects). You must create a bucket before uploading data.
Example code:
Java1BosClient client = new BosClient(config); //Create a BOSClient instance 2 client.createBucket(<BucketName>); //Create a bucket and specify the bucket name -
Upload an object.
An object is the basic data unit in BOS. You can think of an object as a file. For simple object uploads, BOS provides four methods: file upload, data stream upload, binary string upload, and string upload.
Example code:
Java1// Get specified file 2 File file = new File(<FilePath>); //Specify the file path 3 // Upload object as a file 4PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file); 5 // Obtain data stream 6InputStream inputStream = new FileInputStream(<FilePath>); 7 // Upload an object in the form of a data stream 8PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream); 9 // Upload object as binary string 10PutObjectResponse putObjectResponseFromByte = client.putObject(<BucketName>, <ObjectKey>, <byte>); 11 // Upload object in string form 12PutObjectResponse putObjectResponseFromString = client.putObject(<BucketName>, <ObjectKey>, <string>); 13 // Print ETag 14System.out.println(putObjectFromFileResponse.getETag()); -
View the list of objects within a bucket.
Once you've finished uploading a series of files, use the following code to list all objects within the bucket.
Example code:
Java1// Obtain all object information under the specified bucket 2ListObjectsResponse listing = client.listObjects(<BucketName>); 3 // Traverse all objects 4for (BosObjectSummary objectSummary : listing.getContents()) { 5 System.out.println("ObjectKey: " + objectSummary.getKey()); 6 } -
Get the specified object.
Refer to the code below to fetch one or multiple objects.
Example code:
Java1//Obtain the object, with returned result BosObject object 2BosObject object = client.getObject(<BucketName>, <ObjectKey>); 3 // Retrieve ObjectMeta 4ObjectMetadata meta = object.getObjectMetadata(); 5 //Obtain the object's input stream 6InputStream objectContent = object.getObjectContent(); 7 // Process object 8... 9 // Close stream 10objectContent.close();
Complete example
1import java.io.File;
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.io.InputStream;
5import android.os.Bundle;
6import com.baidubce.BceClientException;
7import com.baidubce.BceServiceException;
8import com.baidubce.auth.DefaultBceCredentials;
9import com.baidubce.development.AppSettings;
10import com.baidubce.development.BaseActivity;
11import com.baidubce.development.R;
12import com.baidubce.services.bos.BosClient;
13import com.baidubce.services.bos.BosClientConfiguration;
14import com.baidubce.services.bos.model.BosObject;
15import com.baidubce.services.bos.model.BosObjectSummary;
16import com.baidubce.services.bos.model.CreateBucketResponse;
17import com.baidubce.services.bos.model.ListObjectsResponse;
18import com.baidubce.services.bos.model.ObjectMetadata;
19import com.baidubce.services.bos.model.PutObjectResponse;
20import com.baidubce.util.BLog;
21public class ExampleActivity extends BaseActivity {
22 @Override
23 protected void onCreate(Bundle savedInstanceState) {
24 super.onCreate(savedInstanceState);
25 setContentView(R.layout.activity_main);
26 //Enable BOS SDK runtime logs
27 BLog.enableLog();
28
29 BosClientConfiguration config = new BosClientConfiguration(); ////Initialize a BosClient with STS authentication
30 config.setCredentials(new DefaultBceSessionCredentials(<AccessKeyID>, <SecretAccessKey>, <Token>); //Temporary AK/SK and Token returned by STS
31 config.setEndpoint(<EndPoint>); //the region where the bucket is located
32 final BosClient client = new BosClient(config);
33 new Thread(new Runnable() {
34 @Override
35 public void run() {
36 try {
37 //Create Bucket
38 CreateBucketResponse response = client.createBucket(<BucketName>); //Create a bucket and specify the bucket name
39 System.out.println(response.getLocation());
40 System.out.println(response.getName());
41 //Upload Object
42 File file = new File(<Path>);//Directory of the uploaded file
43 PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
44 System.out.println(putObjectFromFileResponse.getETag());
45 // View Object
46 ListObjectsResponse list = client.listObjects(<BucketName>);
47 for (BosObjectSummary objectSummary : list.getContents()) {
48 System.out.println("ObjectKey: " + objectSummary.getKey());
49 }
50 // Get Object
51 BosObject object = client.getObject(<BucketName>, <ObjectKey>);
52 // Retrieve ObjectMeta
53 ObjectMetadata meta = object.getObjectMetadata();
54 //Obtain the object's input stream
55 InputStream objectContent = object.getObjectContent();
56 // Process object
57 FileOutputStream fos=new FileOutputStream(<Path>);//Directory/filename of the downloaded file
58 byte[] buffer=new byte[2048];
59 int count=0;
60 while ((count=objectContent.read(buffer))>=0) {
61 fos.write(buffer,0,count);
62 }
63 // Close stream
64 objectContent.close();
65 fos.close();
66 System.out.println(meta.getETag());
67 System.out.println(meta.getContentLength());
68 }catch (BceServiceException e) {
69 System.out.println("Error ErrorCode: " + e.getErrorCode());
70 System.out.println("Error RequestId: " + e.getRequestId());
71 System.out.println("Error StatusCode: " + e.getStatusCode());
72 System.out.println("Error Message: " + e.getMessage());
73 System.out.println("Error ErrorType: " + e.getErrorType());
74 } catch (BceClientException e) {
75 System.out.println("Error Message: " + e.getMessage());
76 } catch (IOException e) {
77 // TODO Auto-generated catch block
78 e.printStackTrace();
79 }
80 }
81 }).start();
82 }
83}
Create a new BosClient with STS authentication
BosClient acts as the client for BOS services, offering developers numerous methods to interact with BOS. Before using the SDK to send requests to BOS, ensure you initialize a BosClient instance and configure the required settings.
Note: Android SDK is primarily used for mobile development scenarios. Mobile an untrusted environment, and there is a high risk of directly saving AccessKeyId and SecretAccessKey in the terminal for signing requests. Therefore, it is recommended to use the STS authentication mode. For detailed introduction to STS, please refer to [Temporary Authorization Access](BOS/API Reference/Access control.md#Temporary authorized access).
When using the STS method, you need to first create a BOSClient with STS to execute when calling the API. Currently, BOS STS only supports API calls in the following methods:
- DeleteObject
- PutObject
- ListParts
- GetObject
- DoesBucketExist
- CompleteMultipartUpload
- AbortMultipartUpload
- InitiateMultipartUpload
- UploadPart
Example code: Users may refer to the following code to create a BosClient with STS authentication:
1BosClientConfiguration config = new BosClientConfiguration(); ////Initialize a BosClient with STS authentication
2 config.setCredentials(new DefaultBceSessionCredentials(<AccessKeyID>, <SecretAccessKey>, <Token>); //Temporary AK/SK and Token returned by STS
3 config.setEndpoint(<EndPoint>); //Pass in the domain name of the region where the bucket is located. EndPoint refers to the domain name address of the BOS service in various regions, e.g., Beijing's domain name is bj.bcebos.com
4 BosClient client = new BosClient(config);
1 > **Note:**`EndPoint`parameter must use region-specific domains. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md).
2 >
3 > Currently, the supported regions include "North China-Beijing," "South China-Guangzhou" and "East China-Suzhou." Beijing region: `http://bj.bcebos.com`, Guangzhou region: `http://gz.bcebos.com`, Suzhou region: `http://su.bcebos.com`.
Configure HTTPS access to BOS
BOS supports HTTPS transport protocol. You can use HTTPS to access the BOS service in the BOS Android SDK in the following two ways:
- Specify HTTPS in the endpoint:
1```java
2String endpoint = "https://bj.bcebos.com";
3String ak = "ak";
4String sk = "sk";
5BosClientConfiguration config = new BosClientConfigration();
6config.setEndpoint(endpoint);
7config.setCredentials(new DefaultBceCredentials(ak, sk));
8BosClient client = new BosClient(config);
9```
- Configure HTTPS by calling setProtocol:
1```java
2String endpoint = "bj.bcebos.com"; // endpoint without protocol
3String ak = "ak";
4String sk = "sk";
5BosClientConfiguration config = new BosClientConfigration();
6config.setEndpoint(endpoint);
7config.setCredentials(new DefaultBceCredentials(ak, sk));
8 config.setProtocol(Protocol.HTTPS); // Defaults to HTTP if unspecified
9BosClient client = new BosClient(config);
10```
11 > **Note**: If the endpoint already includes a protocol, the one in endpoint takes effect, and the setProtocol() method will be ignored.
12
13```java
14String endpoint = "http://bj.bcebos.com";
15String ak = "ak";
16String sk = "sk";
17BosClientConfiguration config = new BosClientConfigration();
18config.setEndpoint(endpoint);
19config.setCredentials(new DefaultBceCredentials(ak, sk));
20 config.setProtocol(Protocol.HTTPS); // Invalid operation if specified in endpoint, applicable to HTTP cases
21BosClient client = new BosClient(config);
22```
Configure BosClient
To configure specific parameters for BosClient, pass a BosClientConfiguration object during its construction. BosClientConfiguration serves as the configuration class for BOS services, allowing you to set fundamental network parameters.
Set network parameters
Use BosClientConfiguration to define key network parameters.
- Example code
1```java
2BosClientConfiguration config = new BosClientConfiguration();
3 // Set maximum number of HTTP connections to 10
4config.setMaxConnections(10);
5 // Set TCP connection timeout to 5,000 milliseconds
6config.setConnectionTimeout(5000);
7 // Set timeout for Socket data transmission to 2,000 milliseconds
8config.setSocketTimeout(2000);
9```
-
Parameter description
The following parameters can be configured via BosClientConfiguration:
Parameters Description UserAgent User agent, refers to HTTP’s User-Agent header Protocol Connection protocol type, default value HTTP protocol LocalAddress Local address ConnectionTimeoutInMillis Timeout duration for establishing connections (unit: ms), with a default value of 30000 SocketTimeoutInMillis Timeout duration for data transmission through the opened connections (unit: ms), with a default value of 30000 MaxConnections Maximum allowable HTTP connections, with a default value of 5 RetryPolicy Retry policy for connections SocketBufferSizeInBytes Buffer size for socket operations StreamBufferSize Stream file buffer size Ipv4Priority IPv4 preferred, default value false
