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

示例代码

package TEST.TEST;
 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) {
         // 创建DefaultAcsClient实例并初始化
         DefaultProfile profile = DefaultProfile.getProfile(
             "cn-hangzhou",          // 地域ID
             "your-access-key",      // RAM账号的AccessKey ID
             "your-access-key-secret"); // RAM账号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();
         }    		 
     }
 }