本示例介绍如何使用Alibaba Cloud SDK for Java调用DescribeInstances接口获取ECS实例的配置信息,例如公网IP、ECS实例ID等。

前提条件

在使用本教程之前,请确保已完成以下操作:

  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见 阿里云开发工具包(SDK)
    <dependencies>     <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core --&gt;     <dependency&gt;         <groupId>com.aliyun</groupId>         <artifactId>aliyun-java-sdk-core</artifactId>         <version>4.4.3</version>     </dependency>     <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-ecs-->     <dependency>         <groupId>com.aliyun</groupId>         <artifactId>aliyun-java-sdk-ecs</artifactId>         <version>4.17.4</version>     </dependency> </dependencies>

示例代码

本文操作示例主要以代码形式体现,具体代码如下:

 import com.aliyuncs.profile.DefaultProfile;  import com.aliyuncs.DefaultAcsClient;  import com.aliyuncs.IAcsClient;  import com.aliyuncs.exceptions.ClientException;  import com.aliyuncs.exceptions.ServerException;  import com.aliyuncs.ecs.model.v20140526.*;  public class DescribeInstances {      public static void main(String[] args) {                 // 初始化请求参数         DefaultProfile profile = DefaultProfile.getProfile(                 "<your-region-id>", // 您的可用区ID                 "<your-access-key-id>", // 您的AccessKey ID                 "<your-access-key-secret>"); // 您的AccessKey Secret          IAcsClient client = new DefaultAcsClient(profile);          // 创建API请求并设置参数          DescribeInstancesRequest request = new DescribeInstancesRequest();          request.setPageSize(10);          request.setConnectTimeout(5000); //设置连接超时为5000毫秒          request.setReadTimeout(5000); //设置读超时为5000毫秒          // 发起请求并处理应答或异常          DescribeInstancesResponse response;          try {              response = client.getAcsResponse(request);              for (DescribeInstancesResponse.Instance instance:response.getInstances()) {                  System.out.println(instance.getImageId());                  System.out.println(instance.getInstanceId());                  System.out.println(instance.getPublicIpAddress());              }          } catch (ServerException e) {              e.printStackTrace();          } catch (ClientException e) {              e.printStackTrace();          }                   }  }