Get Object
Simple object get
Users can load the object into a stream by using the following code.
Basic workflow
- Instantiate the BOSClient class.
- By calling the BOSClient.getObject() method, the specified BosObject will be returned.
- Load the BosObject into a stream for further processing.
Example code
1//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();
Note:
- The BosObject includes various details about the object, such as the bucket it belongs to, the object’s name, metadata, and an input stream. Users can read the object's content into a file or memory by interacting with the input stream.
- ObjectMetadata contains information such as the ETag defined during object upload, HTTP headers, and custom metadata.
- Using the getObjectContent() method of BosObject, users can access the input stream of the returned object, enabling them to read and process the object's content.
Complete example
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStream;
4import java.io.InputStreamReader;
5import android.app.Activity;
6import android.os.Bundle;
7import com.baidubce.BceClientException;
8import com.baidubce.BceServiceException;
9import com.baidubce.auth.DefaultBceCredentials;
10import com.baidubce.demo.R;
11import com.baidubce.services.bos.BosClient;
12import com.baidubce.services.bos.BosClientConfiguration;
13import com.baidubce.services.bos.model.BosObject;
14import com.baidubce.services.bos.model.ObjectMetadata;
15public class ExampleActivity extends Activity {
16private String bucketName = <BucketName>;
17private String objectKey = <ObjectKey>;
18@Override
19protected void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.activity_main);
22 new Thread(new Runnable() {
23 @Override
24 public void run() {
25 try {
26 BosClientConfiguration config = new BosClientConfiguration();
27 config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
28 config.setEndpoint(<EndPoint>);
29 BosClient client = new BosClient(config);
30 //Obtain the object, with returned result BosObject object
31 BosObject object = client.getObject(<BucketName>, <ObjectKey>);
32 // Retrieve ObjectMeta
33 ObjectMetadata meta = object.getObjectMetadata();
34 //Obtain the object's input stream
35 InputStream objectContent = object.getObjectContent();
36 // Process object
37 FileOutputStream fos=new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/1/file");
38 byte[] buffer=new byte[<bufferSize>];
39 int count=0;
40 while ((count=objectContent.read(buffer))>=0) {
41 fos.write(buffer,0,count);
42 }
43 System.out.println(meta.getETag());
44 System.out.println(meta.getContentLength());
45 // Close stream
46 objectContent.close();
47 fos.close();
48 } catch (BceServiceException e) {
49 System.out.println("Error ErrorCode: " + e.getErrorCode());
50 System.out.println("Error RequestId: " + e.getRequestId());
51 System.out.println("Error StatusCode: " + e.getStatusCode());
52 System.out.println("Error Message: " + e.getMessage());
53 System.out.println("Error ErrorType: " + e.getErrorType());
54 } catch (BceClientException e) {
55 System.out.println("Error Message: " + e.getMessage());
56 } catch (IOException e) {
57 // TODO Auto-generated catch block
58 e.printStackTrace();
59 }
60 }
61 }).start();
62}}
Obtain object via GetObjectRequest
To unlock more capabilities, GetObjectRequest can be used to retrieve objects.
Basic workflow
- Create an instance of the GetObjectRequest class.
- Invoke the setRange() method on GetObjectRequest to retrieve specific byte ranges from the object.
- Execute the client.getObject() operation.
Example code
1// Create GetObjectRequest
2GetObjectRequest getObjectRequest = new GetObjectRequest(<BucketName>, <ObjectKey>);
3 // Obtain data within the 0~100 byte range
4getObjectRequest.setRange(0, 100);
5 //Obtain the object, with returned result BosObject object
6BosObject object = client.getObject(getObjectRequest);
Note: The setRange() method in GetObjectRequest allows users to specify a range for the returned object. This feature can be used to implement segmented downloads and resumable uploads.
Obtain download progress
Users can track download progress via a callback function.
The SDK offers a download progress callback API, which allows you to define necessary operations during the upload process, such as updating the API.
1public interface BceProgressCallback<T extends AbstractBceRequest> {
2 // request is the download request
3 // currentSize is the current download size (unit: byte)
4 // totalSize is the total size to be downloaded in this request (unit: byte)
5 void onProgress(T request, long currentSize, long totalSize);
6 }
Example code
1GetObjectRequest request = new GetObjectRequest()
2 .withBucketName(this.bucketName)
3 .withKey(objectKey)
4 .withRange(0, 5);
5request.setProgressCallback(new BosProgressCallback<GetObjectRequest>() {
6 @Override
7 public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
8 Log.e(currentSize + "", totalSize + "");
9 }
10});
11InputStream input = this.client.getObject(request).getObjectContent();
Note: The download progress interface differs from the upload progress interface. It is not possible to specify the fragment size of the increase in the download volume during each callback.
Download object to a specified path
Users can use the following code to directly download an object to a specified path.
Basic workflow
- Create an instance of the GetObjectRequest class.
- Execute the client.getObject() operation.
- Download an object directly to a specified path.
Example code
1// Create GetObjectRequest
2GetObjectRequest getObjectRequest = new GetObjectRequest(<BucketName>, <ObjectKey>);
3 // Download object to file
4ObjectMetadata objectMetadata = client.getObject(getObjectRequest, new File("/path/to/file","w+"));
Note: When using the above method to directly download an object to a specified path, the method returns an ObjectMetadata object.
Obtain the storageClass of an object
The storage classes of an object are categorized as STANDARD (standard storage), STANDARD_IA (infrequent access storage), COLD (cold storage), and ARCHIVE (archive storage).
Example code
1public void getObjectStorageClass(){
2 //...
3ObjectMetadata meta = client.getObjectMetadata(bucketName, key);
4String storageClass = meta.getStorageClass();
5}
Obtain only ObjectMetadata
The getObjectMetadata() method retrieves only the ObjectMetadata, without obtaining the object itself.
Example code
1ObjectMetadata objectMetadata = client.getObjectMetadata(<BucketName>, <ObjectKey>);
Get object URL
The following code allows you to get the URL of a specific object, which is commonly used for temporarily sharing the object's URL with others.
Basic workflow
- Instantiate the BOSClient class.
- Call the BOSClient.generatePresignedUrl() method.
- The method returns the URL of the object.
Example code
1URL url = client.generatePresignedUrl(<BucketName>, <ObjectKey>, <ExpirationInSeconds>);
Note:
ExpirationInSecondsis the specified URL validity period, calculated from the current time. It is an optional parameter, and the system default value is 1,800 s if not configured. To set a permanent non-expiration time, theExpirationInSecondsparameter can be set to -1. You cannot set it to any other negative value.
Complete example
1import java.net.URL;
2import android.app.Activity;
3import android.content.Intent;
4import android.net.Uri;
5import android.os.Bundle;
6import com.baidubce.BceClientException;
7import com.baidubce.BceServiceException;
8import com.baidubce.auth.DefaultBceCredentials;
9import com.baidubce.demo.R;
10import com.baidubce.services.bos.BosClient;
11import com.baidubce.services.bos.BosClientConfiguration;
12public class ExampleActivity extends Activity {
13private String bucketName = <BucketName>;
14private String objectKey = <ObjectKey>;
15@Override
16protected void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.activity_main);
19 new Thread(new Runnable() {
20 @Override
21 public void run() {
22 try {
23 BosClientConfiguration config = new BosClientConfiguration();
24 config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
25 config.setEndpoint(<EndPoint>);
26 BosClient client = new BosClient(config);
27 //Obtain the object URL
28 URL url = client.generatePresignedUrl(<BucketName>, <ObjectKey>, 2000);
29 Uri uri = Uri.parse(url.toString());
30 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
31 // Execute URL
32 startActivity(intent);
33 } catch (BceServiceException e) {
34 System.out.println("Error ErrorCode: " + e.getErrorCode());
35 System.out.println("Error RequestId: " + e.getRequestId());
36 System.out.println("Error StatusCode: " + e.getStatusCode());
37 System.out.println("Error Message: " + e.getMessage());
38 System.out.println("Error ErrorType: " + e.getErrorType());
39 } catch (BceClientException e) {
40 System.out.println("Error Message: " + e.getMessage());
41 }
42 }
43 }).start();
44}}
