Query the region of a bucket (Java SDK V2)

Updated at:

Query the region of a bucket by calling the GetBucketLocation operation with OSS Java SDK V2.

Prerequisites

  • OSS Java SDK V2 installed. If you use Maven, add the com.aliyun:alibabacloud-oss-v2 dependency to pom.xml.

  • Access credentials configured by using environment variables. The sample code in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

Permissions

By default, an Alibaba Cloud account has full permissions. A RAM user or RAM role under the account has no permissions by default and must be granted the required permissions by the Alibaba Cloud account or an account administrator.

API

Action

Description

GetBucketLocation

oss:GetBucketLocation

Query the region in which a bucket resides.

Sample code

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

public class GetBucketLocationSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {

            GetBucketLocationResult result = client.getBucketLocation(GetBucketLocationRequest.newBuilder()
                            .bucket(bucket)
                    .build());

            System.out.printf("status code:%d, request id:%s%n",
                    result.statusCode(), result.requestId());
            System.out.printf("Location: %s%n", result.locationConstraint());

        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

References