Help Center> Object Storage Service> Android> Object Download> Performing a Streaming Download
Updated on 2024-05-09 GMT+08:00

Performing a Streaming Download

If you have any questions during development, post them on the Issues page of GitHub. For details about parameters and usage of each API, see the API Reference

Sample code:

// Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID.
// Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
String ak = System.getenv("ACCESS_KEY_ID");
String sk = System.getenv("SECRET_ACCESS_KEY_ID");
String endPoint = "https://your-endpoint";
// Create an instance of ObsClient.
final ObsClient obsClient = new ObsClient(ak, sk, endPoint);

ObsObject obsObject = obsClient.getObject("bucketname", "objectname");

// Obtain the object content.
Log.i("GetObject", "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);
}
 
Log.i("GetObject", new String(bos.toByteArray()));
bos.close();
input.close();
  • After ObsClient.getObject is called, an instance of ObsObject will be returned. This instance contains the residing bucket, name, properties, and input streams of the object.
  • You can operate the input streams of an object to read and write the object to a local file or to the memory.
  • Due to HTTP coding restrictions, non-ASCII characters cannot be sent. The SDK uses a URL to decode the information in the response header. For example, if content-disposition in your metadata is set to attachment; filename="%E4%B8%AD%E6%96%87.txt", the result obtained by the SDK is attachment; filename="Chinese characters.txt".
  • If you do not need the SDK to decode for you, call GetObjectRequest.setIsEncodeHeaders(false) to disable auto decoding.
  • You can also call obsObject.getMetadata().getOriginalHeaders() to obtain information about all original response headers.

Object input streams obtained by ObsObject.getObjectContent must be closed explicitly. Otherwise, resource leakage occurs.