All Products
Search
Document Center

Elastic Compute Service:ECS Java SDK V2.0 call examples

Last Updated:Apr 10, 2026

This topic describes how to install and use the Java software development kit (SDK) V2.0. An example is provided to show how to call the DescribeInstances API operation to query the details of one or more Elastic Compute Service (ECS) instances.

Prerequisites

  1. The AccessKey of an Alibaba Cloud account provides full access to your resources, which poses a high security risk if the AccessKey is leaked. We recommend that you create a Resource Access Management (RAM) user and grant the RAM user only the required permissions. Then, use the AccessKey of the RAM user to call API operations. For more information, see Create an AccessKey.

  2. You have granted the RAM user permissions to manage ECS resources. The example code in this topic shows a query operation. In this example, the AliyunECSReadonlyAccess system policy is used. You can grant custom permissions as needed.

    1. Use custom policies.

      For more information about how to create custom policies, see Create a custom policy and Authorization information.

      ECS provides custom policy examples based on best practices. You can use these examples to quickly create custom policies that meet your business needs. For more information, see Custom policies.

    2. Use system policies.

      For information about all system policies that ECS supports and their permission descriptions, see System policies for ECS.

  3. Configure the AccessKey using environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

Install the SDK

You can install the Java SDK in multiple ways. This topic uses Apache Maven as an example. For more information about other installation methods, see SDK Center.

Open the pom.xml file of your Maven project. Add the dependency to the <dependencies> node and refresh the Maven configuration.

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>ecs20140526</artifactId>
  <version>5.3.0</version>
</dependency>

Use the SDK

1. Initialize the client

You can use multiple types of credentials to initialize a client, such as an AccessKey or a Security Token Service (STS) token. For more information about other credential types, see Manage access credentials. This example shows how to initialize a client using an AccessKey.

import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For the endpoint, see https://api.aliyun.com/product/Ecs
                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }
}

2. Create a request object for the API operation

Before you create the request object, view the API documentation for the operation to obtain parameter information.

Note

Request object naming convention: {APIName}Request. For example, the request object for the DescribeInstances API operation is DescribeInstancesRequest.

// Create a request object.
DescribeInstancesRequest request = new DescribeInstancesRequest().setRegionId("cn-hangzhou");

3. Initiate a call

When you use the client to call an OpenAPI operation, you can set runtime parameters, such as timeout and proxy configurations. For more information, see Advanced configurations.

Note

Response object naming convention: {APIName}Response. For example, the response object for the DescribeInstances API operation is DescribeInstancesResponse.

// Set runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
// Call the DescribeInstances API operation.
DescribeInstancesResponse response = client.describeInstancesWithOptions(request, runtime);
System.out.println(response.body.toMap());

4. Handle exceptions

The Java SDK provides a detailed exception classification. Exceptions are classified into two main types: TeaUnretryableException and TeaException.

  • TeaUnretryableException: This exception is typically thrown because of network issues after the maximum number of retries is reached.

  • TeaException: This exception is primarily for business errors.

You must take appropriate measures to handle exceptions, such as propagating exceptions, recording logs, and attempting recovery, to ensure system robustness and stability.

5. Complete example

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For the endpoint, see https://api.aliyun.com/product/Ecs
                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }

    public static void main(String[] args) {
        try {
            Client client = Sample.createClient();
            // Create a request object.
            DescribeInstancesRequest request = new DescribeInstancesRequest()
                    .setRegionId("cn-hangzhou");
            // Set runtime parameters.
            RuntimeOptions runtime = new RuntimeOptions();
            // Call the DescribeInstances API operation.
            DescribeInstancesResponse response = client.describeInstancesWithOptions(request, runtime);
            System.out.println(response.body.toMap());
        } catch (TeaUnretryableException ue) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your projects.
            ue.printStackTrace();
            // Print the error message.
            System.out.println(ue.getMessage());
            // Print the request record to query the request information when the error occurred.
            System.out.println(ue.getLastRequest());
        } catch (TeaException e) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your projects.
            e.printStackTrace();
            // Print the error code.
            System.out.println(e.getCode());
            // Print the error message, which includes the RequestId.
            System.out.println(e.getMessage());
            // Print the specific error content returned by the server.
            System.out.println(e.getData());
        } catch (Exception e) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your projects.
            e.printStackTrace();
        }
    }
}

Scenario-based examples

More information

In addition to the preceding methods, you can use generalized calls to call ECS OpenAPI operations. For more information, see Generalized calls.

If you are using SDK V1.0 and want more information, see Java SDK V1.0.