The Cloud Control API Java SDK provides standardized interfaces to manage the full lifecycle of your Alibaba Cloud resources, including creating, querying, updating, and deleting resources. The SDK simplifies development so you can focus on business logic instead of low-level API details.
Prerequisites
-
To call the Cloud Control API, you need an AccessKey pair. Because the AccessKey pair of your Alibaba Cloud account has full permissions, we recommend that you create a RAM user and use its AccessKey pair instead. For more information, see Create a RAM user and Create an AccessKey.
-
You must configure access credentials to call the Cloud Control API. A common credential type is
AccessKey (AK). To prevent credential leaks, store them as environment variables.NoteThis topic uses the
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables as examples. -
Before calling the Cloud Control API, ensure the RAM user has the required permissions for the target resources. For more information, see Manage permissions for a RAM user.
-
For fine-grained control, you can create a custom permission policy. For instructions, see Create a custom policy.
NoteThis topic uses listing VPC resources as an example.
-
Quick authorization: Grant the AliyunCloudControlAPIFullAccess policy, which provides full permissions for all Cloud Control API operations.
-
Fine-grained authorization: Create a custom permission policy that grants only the permissions needed, such as listing VPC resources.
-
Requirements
JDK version 1.8 or later.
Add SDK dependency
-
Log on to SDK Center and select the Cloud Control API product (for example, if you want to call an API to list resources).
-
On the Installation page, select Java from the All Languages drop-down list. You can find the installation method for the Cloud Control API SDK on the Quick Start tab.
<dependency> <groupId>com.aliyun</groupId> <artifactId>cloudcontrol20220830</artifactId> <version>1.1.1</version> </dependency>
Call the API
This section shows how to call the GetResources API to list VPC resources.
Initialize the client
All Cloud Control API calls in the SDK go through a client. To initialize the client, specify the service endpoint for your region. You can find the endpoint in the Service Region section of the Cloud Control API Portal. For more information about service endpoints, see Supported Regions. This example initializes the client with an AccessKey pair. For other initialization methods, see Manage access credentials for the Java SDK.
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// System.getenv() retrieves the AccessKey from environment variables.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Service endpoint
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
// Initialize the client by using the default credentials provider chain.
// com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
// com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// .setCredential(credentialClient);
// config.endpoint = "cloudcontrol.aliyuncs.com";
// com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);The getenv() function reads an environment variable. If you set environment variables named ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET on your machine, getenv() retrieves their values.
When you initialize the credentials client without parameters, the Credentials tool uses the default credentials provider chain. For the retrieval logic of default credentials, see default credentials provider chain.
Define the request path
// Request path
String requestPath = "/api/v1/providers/Aliyun/products/VPC/resources/VPC";The request path format is /api/v1/providers/{provider}/products/{product}/resources/{resourceTypeCode}.
The following table describes the variables in the request path.
Field
Description
Example value
{provider}The name of the cloud provider. Only
Aliyunis supported.Aliyun{product}The product code. You can obtain it by calling the ListProducts operation.
VPC{resourceTypeCode}The resource code. You can obtain it by calling the ListProducts operation.
VPCYou can determine if a resource has a parent resource by checking the format of its
resourceType:ResourceType format
Description
Example value
****If the value does not contain a
/, the resource does not have a parent resource.VPC****/****A
/in a resource type indicates that the resource has a parent resource. For example, ApsaraDB for Redis has resources for Redis instances (DBInstance) and database accounts (DBInstance/Account). The resource type of a database account is "DBInstance/Account", where "DBInstance" is the resource type of its parent resource, the Redis instance.DBInstance/AccountFor more information, see Parent and child resources.
Create a request object
Request objects are instances of classes named <OperationName>Request. Set API parameters using the properties of the request object.
// Filter conditions (optional)
// java.util.Map < String, Object > filter = TeaConverter.buildMap(
// new TeaPair("IsDefault", true), // Specifies whether the VPC is the default VPC.
// new TeaPair("ResourceGroupId", "<YOUR_RESOURCEGROUPID>"), // The resource group ID.
// new TeaPair("DhcpOptionsSetId", "<YOUR_DHCPOPTIONSSETID>"), // The ID of the DHCP options set.
// new TeaPair("VpcId", "<YOUR_VPCID>"), // The VPC ID.
// new TeaPair("VpcName", "<YOUR_VPCNAME>") // The VPC name.
// );
// Create a request object.
com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
.setRegionId("cn-hangzhou") // The region ID.
// .setFilter(filter) // The query filter conditions.
// .setNextToken("") // The token for the next page of results.
.setMaxResults(2); // The number of results per page for paginated queries.Send the request
API calls use client methods named <operationName>WithOptions, where <operationName> is the API operation name in camelCase. This method takes four arguments: the request path, the request object, header parameters, and runtime options. Runtime options configure request behavior such as timeouts and proxy settings.
// Define runtime options.
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// // Ignore SSL certificate verification.
// runtime.ignoreSSL = true;
// // Proxy configuration.
// runtime.httpProxy = "http://127.0.0.1:9898";
// runtime.httpsProxy = "http://user:password@127.0.0.1:8989";
// runtime.noProxy = "127.0.0.1,localhost";
// // Connection timeout.
// runtime.connectTimeout = 5000;
// // Read timeout.
// runtime.readTimeout = 10000;
// // Enable the automatic retry mechanism.
// runtime.autoretry = true;
// // Set the maximum number of retries.
// runtime.maxAttempts = 3;
// Use headers to customize request headers, which can override defaults or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap<>();
// headers.put("x-acs-action", "GetResources"); // Set the API operation name.
// Send the request.
GetResourcesResponse getResourcesResponse = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);Handle exceptions
The Java V2.0 SDK classifies exceptions into two types: TeaUnretryableException and TeaException.
TeaUnretryableException: Thrown after the maximum number of retries is reached, typically caused by network issues.
TeaException: An exception that indicates service errors.
Implement robust exception handling to log errors, manage recovery, and ensure system stability.
Code example
FAQ
When calling an API, I receive the error "You are not authorized to perform this operation".
Cause: The RAM user associated with the AccessKey pair does not have the required permissions.
Solution: Grant the RAM user the required API permissions. For instructions, see Manage permissions for a RAM user.
For example, if you receive the "You are not authorized to perform this operation" error when calling the GetResources API, you can create a custom permission policy and grant the corresponding permissions to the RAM user.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "cloudcontrol:List*", "Resource": "*" }, { "Effect": "Allow", "Action": "vpc:DescribeVpcs", "Resource": "*" } ] }When calling an API, I receive the error "Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null".
Cause: The
AccessKeyenvironment variables are not configured correctly.Solution: