You need to enable JavaScript to run this app.
导航
普通下载(Android SDK)
最近更新时间:2024.02.04 18:31:00首次发布时间:2022.12.01 16:31:39

普通下载指的是通过 SDK 的 getObject 从指定桶中下载完整对象。在使用此接口之前,请确保您拥有对此对象的读访问权限。

示例代码

以下代码展示如何下载一个对象。

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosException;
import com.volcengine.tos.model.object.GetObjectV2Input;
import com.volcengine.tos.model.object.GetObjectV2Output;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GetObjectInStringExample extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = "your access key";
        String secretKey = "your secret key";

        String bucketName = "your bucket name";
        String objectKey = "your object key";
        String securityToken = "your security token";

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);
        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey, securityToken);

        Thread tosThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    GetObjectV2Input input = new GetObjectV2Input().setBucket(bucketName).setKey(objectKey);
                    // 以下代码展示如何将数据下载到本地文件
                    try(GetObjectV2Output output = tos.getObject(input);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(output.getContent()))) {
                        Log.i("getObject", "begin to read content in object.");
                        while (true) {
                            String line = reader.readLine();
                            if (line == null) {
                                break;
                            }
                            Log.i("getObject", line);
                        }
                        Log.i("getObject", "getObject succeed, object's metadata is " + output.getGetObjectBasicOutput());
                    } catch (IOException e) {
                        Log.e("IOException", "read data in object failed");
                        e.printStackTrace();
                    }
                } catch (TosException e) {
                    if (e.getStatusCode() == 404) {
                        // 下载不存在的对象会返回404
                        Log.e("TosException", "the object you want to download is not found");
                    } else {
                        Log.e("TosException", "getObject failed");
                    }
                    e.printStackTrace();
                }
            }
        });

        tosThread.start();
    }
}

相关文档

关于下载对象的 API 文档,请参见 GetObject