查看Bucket列表
更新时间:2022-10-21
基本流程
- 创建BOSClient类的实例。
- 执行BOSClient.listBuckets()方法,会返回ListBucketsResponse类的实例。
- 对ListBucketsResponse类型实例可以进行getBuckets()/getOwner()/getMetadata()操作。
示例代码
如下代码可以列出用户所有的Bucket:
List<BucketSummary> buckets = client.listBuckets().getBuckets();
// 遍历Bucket
for (BucketSummary bucket : buckets) {
System.out.println(bucket.getName());
}
如下代码可以列出Bucket的Owner:
User usr = client.listBuckets().getOwner();
System.out.println(usr.getDisplayName());
System.out.println(usr.getId());
如下代码可以列出Bucket的Metadata:
BosResponseMetadata metaData = client.listBuckets().getMetadata();
System.out.println(metaData.getBceRequestId());
System.out.println(metaData.getBceContentSha256());
System.out.println(metaData.getContentLength());
System.out.println(metaData.getEtag());
System.out.println(metaData.getExpires());
System.out.println(metaData.getContentMd5());
System.out.println(metaData.getContentDisposition());
System.out.println(metaData.getLastModified());
注意:Bucket如果没有设置这些参数,返回时可能为空。
完整示例
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import com.baidubce.BceClientException;
import com.baidubce.BceServiceException;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.development.R;
import com.baidubce.model.User;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.BosResponseMetadata;
import com.baidubce.services.bos.model.BucketSummary;
import com.baidubce.services.bos.model.CreateBucketResponse;
import com.baidubce.services.bos.model.ListBucketsResponse;
public class ExampleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
config.setEndpoint(<EndPoint>);
BosClient client = new BosClient(config);
ListBucketsResponse bucketsResponse = client.listBuckets() ;
// 获得Bucket列表
List<BucketSummary> buckets = bucketsResponse.getBuckets();
for (BucketSummary bucket : buckets) {
System.out.println(bucket.getName());
}
// 获得Bucket的Owner
User user = bucketsResponse.getOwner();
System.out.println(user.getDisplayName());
System.out.println(user.getId());
} 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());
}
}
}).start();
}
}