全部產品
Search
文件中心

Cloud Control API:通過SDK實現資源管理

更新時間:Mar 07, 2025

此教程示範如何通過SDK調用雲控制API實現資源管理。將使用Java語言,以Virtual Private Cloud的交換器為例,示範如何整合SDK,查詢資源中繼資料,如何建立、查詢、更新與刪除資源,以及遇到雲控制API採用非同步作業處理任務時如何查詢任務狀態。

前提條件

  1. RAM使用者:

    • 由於阿里雲帳號(主帳號)擁有資源的所有許可權,其AccessKey一旦泄露風險巨大,所以建議您使用滿足最小化許可權需求的RAM使用者的AccessKey。具體操作方式請參見建立AccessKey

    • 給RAM使用者授予操作Virtual Private Cloud相關資源的許可權。此教程涉及VPC的vSwitch多種操作,所以選擇系統權限原則AliyunVPCFullAccess,您在使用的時候可以根據需求進行自訂授權,請參見建立自訂權限原則

    • 在環境變數中配置AccessKey,具體操作步驟請參見在Linux、macOS和Windows系統配置環境變數

  2. VPC

    您需要有一個VPC資源,用於交換器的綁定,如果您沒有VPC,請參見建立和管理專用網路

  3. 資源中繼資料

    資源管理是基於資源中繼資料的操作,因此您需要熟悉資源中繼資料

  4. 同步操作與非同步作業

    此教程中建立資源和刪除資源的請求,雲控制API處理任務時採用非同步作業,你需要瞭解同步操作與非同步作業的概念。雲控制API採用非同步處理時,查詢任務狀態參見教程中的查詢任務

  5. Java

    最低要求Java 8

初始化專案

引入雲控制API的SDK,擷取環境變數中的AccessKey。

  1. 在專案中引入SDK,具體參見安裝SDK,SDK能夠協助您高效的整合與使用雲控制API。本例中,SDK引入如下:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>cloudcontrol20220830</artifactId>
        <version>1.1.1</version>
    </dependency>
  2. 建立一個ExampleDemo類,用於實現資源管理。ExampleDemo類中添加createClient方法,用於擷取環境變數中的AccessKey,初始化帳號Client。樣本如下:

    /**
     * 初始化帳號Client
     * @return Client
     */
    public static Client createClient() throws Exception {
        // 工程代碼泄露可能會導致 AccessKey 泄露,並威脅帳號下所有資源的安全性。以下程式碼範例僅供參考。
        Config config = new Config()
                // 必填,請確保代碼運行環境設定了環境變數 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填,請確保代碼運行環境設定了環境變數 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 請參考 https://api.aliyun.com/product/cloudcontrol
        config.endpoint = "cloudcontrol.aliyuncs.com";
        return new Client(config);
    }

查詢資源類型的詳情

通過產品code與資源類型code,查詢資源類型的詳情,返回資料為資源中繼資料。後續的建立、查詢、列舉和刪除等資源管理操作都是基於資源中繼資料。

  1. 調用GetResourceType,擷取資源類型的詳情。此教程的樣本為Virtual Private Cloud的交換器,Virtual Private Cloud的產品code為VPC,交換器的資源類型code為vSwitch。調用樣本如下:

    說明

    產品code和資源code的擷取方式,請參見:產品code和資源code哪裡擷取?

    /**
     * 查詢資源類型的詳情
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“vSwitch”
     * @param client           帳號client
     * @return resourceTypeWithOptions 返回對象
     */
    public GetResourceTypeResponse getResourceType(String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resourceTypes/" + resourceTypeCode;
        com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders getResourceTypeHeaders = new com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders()
                .setXAcsAcceptLanguage("zh_CH");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 複製代碼運行請自行列印 API 的傳回值
        GetResourceTypeResponse resourceTypeWithOptions = client.getResourceTypeWithOptions(requestPath, getResourceTypeHeaders, runtime);
        return resourceTypeWithOptions;
    }
  2. 返回body為vSwitch的資源中繼資料,解讀資源中繼資料請參見GetResourceType - 查詢資源類型的詳情,此次調用返回body如下:

    resourceTypeWithOptions.getBody()

    {
      "requestId": "DF147125-4F39-57EF-8E9C-554FE0E3AB77",
      "resourceType": {
        "product": "VPC",
        "listResponseProperties": [
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/CidrBlock",
          "/properties/Tags/items",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/Status",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Ipv6CidrBlock",
          "/properties/CreateTime",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/Tags/items/properties/TagKey",
          "/properties/ZoneId",
          "/properties/Tags",
          "/properties/IsDefault",
          "/properties/AvailableIpAddressCount"
        ],
        "updateOnlyProperties": [
          
        ],
        "readOnlyProperties": [
          "/properties/Status",
          "/properties/CreateTime",
          "/properties/AvailableIpAddressCount"
        ],
        "createOnlyProperties": [
          "/properties/VpcIpv6CidrBlock"
        ],
        "listOnlyProperties": [
          
        ],
        "primaryIdentifier": "/properties/VSwitchId",
        "getOnlyProperties": [
          
        ],
        "required": [
          "CidrBlock",
          "VpcId",
          "ZoneId"
        ],
        "publicProperties": [
          "/properties/RouteTableId",
          "/properties/CidrBlock",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/AvailableIpAddressCount",
          "/properties/CreateTime",
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/VpcId",
          "/properties/ZoneId",
          "/properties/Status",
          "/properties/RegionId",
          "/properties/IsDefault",
          "/properties/Ipv6CidrBlock",
          "/properties/Tags",
          "/properties/Tags/items",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Tags/items/properties/TagKey"
        ],
        "filterProperties": [
          "/properties/VSwitchName",
          "/properties/ResourceGroupId",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/VSwitchId",
          "/properties/ZoneId",
          "/properties/IsDefault"
        ],
        "getResponseProperties": [
          "/properties/ResourceGroupId",
          "/properties/CidrBlock",
          "/properties/VSwitchName",
          "/properties/Tags/items",
          "/properties/Description",
          "/properties/VSwitchId",
          "/properties/Status",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Ipv6CidrBlock",
          "/properties/CreateTime",
          "/properties/RouteTableId",
          "/properties/VpcId",
          "/properties/Tags/items/properties/TagKey",
          "/properties/ZoneId",
          "/properties/Tags",
          "/properties/IsDefault",
          "/properties/AvailableIpAddressCount"
        ],
        "handlers": {
          "get": {
            "permissions": [
              "vpc:DescribeVSwitchAttributes",
              "vpc:ListTagResources"
            ]
          },
          "create": {
            "permissions": [
              "vpc:CreateVSwitch"
            ]
          },
          "update": {
            "permissions": [
              "vpc:TagResources",
              "vpc:UnTagResources",
              "vpc:ModifyVSwitchAttribute"
            ]
          },
          "list": {
            "permissions": [
              "vpc:DescribeVSwitches"
            ]
          },
          "delete": {
            "permissions": [
              "vpc:DeleteVSwitch"
            ]
          }
        },
        "deleteOnlyProperties": [
          
        ],
        "updateTypeProperties": [
          "/properties/Description",
          "/properties/VSwitchName",
          "/properties/Ipv6CidrBlock",
          "/properties/Tags",
          "/properties/Tags/items",
          "/properties/Tags/items/properties/TagValue",
          "/properties/Tags/items/properties/TagKey"
        ],
        "properties": {
          "Status": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "代表資源狀態的資源屬性欄位",
            "readOnly": true,
            "sensitive": false,
            "title": "資源狀態",
            "type": "string",
            "updateType": false
          },
          "IsDefault": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "description": "是否是該可用性區域的預設交換器。",
            "readOnly": true,
            "sensitive": false,
            "title": "是否是該可用性區域的預設交換器。",
            "type": "boolean",
            "updateType": false
          },
          "RouteTableId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交換器關聯路由表ID",
            "readOnly": true,
            "sensitive": false,
            "title": "交換器關聯路由表ID",
            "type": "string",
            "updateType": false
          },
          "Description": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交換器的描述資訊。",
            "readOnly": false,
            "sensitive": false,
            "title": "交換器的描述資訊。",
            "type": "string",
            "updateType": true
          },
          "ResourceGroupId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交換器所屬的資源群組ID。",
            "readOnly": true,
            "sensitive": false,
            "title": "交換器所屬的資源群組ID。",
            "type": "string",
            "updateType": false
          },
          "ZoneId": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "代表zone的資源屬性欄位",
            "readOnly": false,
            "sensitive": false,
            "title": "可用性區域ID",
            "type": "string",
            "updateType": false
          },
          "VSwitchId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交換器的ID。",
            "readOnly": false,
            "sensitive": false,
            "title": "交換器的ID。",
            "type": "string",
            "updateType": false
          },
          "AvailableIpAddressCount": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "format": "int64",
            "pattern": "",
            "description": "交換器中可用的IP地址數量。",
            "readOnly": true,
            "sensitive": false,
            "title": "交換器中可用的IP地址數量。",
            "type": "integer",
            "updateType": false
          },
          "CreateTime": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "交換器的建立時間。",
            "readOnly": true,
            "sensitive": false,
            "title": "交換器的建立時間。",
            "type": "string",
            "updateType": false
          },
          "CidrBlock": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "交換器的網段。",
            "readOnly": false,
            "sensitive": false,
            "title": "交換器的網段。",
            "type": "string",
            "updateType": false
          },
          "VpcId": {
            "isRequired": true,
            "extMonitorInfo": false,
            "description": "VPC的ID。",
            "readOnly": false,
            "sensitive": false,
            "title": "VPC的ID。",
            "type": "string",
            "updateType": false
          },
          "VSwitchName": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交換器的名稱。",
            "readOnly": false,
            "sensitive": false,
            "title": "交換器的名稱。",
            "type": "string",
            "updateType": true
          },
          "VpcIpv6CidrBlock": {
            "isRequired": false,
            "extMonitorInfo": false,
            "default": "",
            "deprecated": false,
            "pattern": "",
            "description": "VPC的IPv6網段。",
            "operatePrivateType": [
              "create"
            ],
            "readOnly": false,
            "sensitive": false,
            "title": "VPC的IPv6網段。",
            "type": "string",
            "updateType": false
          },
          "RegionId": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "代表region的資源屬性欄位",
            "readOnly": false,
            "sensitive": false,
            "title": "地區ID",
            "type": "string",
            "updateType": false
          },
          "Ipv6CidrBlock": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "交換器的IPv6網段。",
            "readOnly": false,
            "sensitive": false,
            "title": "交換器的IPv6網段。",
            "type": "string",
            "updateType": true
          },
          "Tags": {
            "isRequired": false,
            "extMonitorInfo": false,
            "description": "標籤結構體",
            "readOnly": false,
            "sensitive": false,
            "title": "標籤",
            "type": "array",
            "items": {
              "extMonitorInfo": false,
              "deprecated": false,
              "description": "標籤結構體",
              "sensitive": false,
              "title": "標籤結構體",
              "type": "object",
              "properties": {
                "TagKey": {
                  "isRequired": false,
                  "extMonitorInfo": false,
                  "description": "標籤的索引值。",
                  "readOnly": false,
                  "sensitive": false,
                  "title": "標籤的索引值。",
                  "type": "string",
                  "updateType": true
                },
                "TagValue": {
                  "isRequired": false,
                  "extMonitorInfo": false,
                  "description": "標籤的取值。",
                  "readOnly": false,
                  "sensitive": false,
                  "title": "標籤的取值。",
                  "type": "string",
                  "updateType": true
                }
              },
              "updateType": true
            },
            "updateType": true
          }
        },
        "sensitiveInfoProperties": [
          
        ],
        "info": {
          "deliveryScope": "zone",
          "chargeType": "free",
          "description": "交換器",
          "title": " 交換器"
        },
        "resourceType": "VSwitch"
      }
    }

建立資源

建立一個交換器,此交換器將用於後續的更新、查詢和刪除等操作。

  1. 調用CreateResource,根據資源中繼資料填寫請求參數。調用樣本如下:

    /**
     * 建立資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“vSwitch”
     * @param client           RAM使用者client
     * @return resourceWithOptions 返回對象
     */
    public CreateResourceResponse createResource(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 參數集合
        Map body = new HashMap();
        body.put("VpcId", "vpc-m5esjf3a6b380olet****");  // VPC的ID
        body.put("CidrBlock", "172.16.24.0/24");  // 交換器的網段。
        body.put("ZoneId", "cn-qingdao-b");  // 可用性區域ID 
        CreateResourceRequest createResourceRequest = new CreateResourceRequest()
                .setRegionId(regionId)
                .setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        CreateResourceResponse resourceWithOptions = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
        return resourceWithOptions;
    }
  2. 此次調用成功,返回statusCode=202,說明為非同步作業,需要進一步查詢任務狀態,記錄taskId,用於查詢任務,請參見查詢任務。同時,記錄resourceId,用於後續步驟中的查詢資源、更新資源與刪除資源等操作。返回body如下:

    resourceWithOptions.getBody()

    {
      "resourceId": "vsw-m5eaburrn73mdpemo****",
      "requestId": "4F7069A4-3CA8-5A48-9D3D-40A1302CBD1B",
      "resourcePath": "VSwitch/vsw-m5eaburrn73mdpemo****",
      "taskId": "task-5057a4fbef2bcffe44d6b3590****"
    }

列舉資源

  1. 調用GetResources,列舉所有vSwitch資源。調用樣本如下:

    /**
     * 列舉資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“vSwitch”
     * @param client           RAM使用者client
     * @return resourcesWithOptions 返回對象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        GetResourcesRequest getResourcesRequest = new GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }
  2. 此次調用成功,返回body如下:

    resourcesWithOptions.getBody()

    {
      "maxResults": 10,
      "nextToken": "2",
      "requestId": "1B5258F0-656F-5005-9FA7-33845FD9FE33",
      "resources": [
       ...,
        {
          "resourceId": "vsw-m5eaburrn73mdpemo****",
          "resourceAttributes": {
            "IsDefault": false,
            "Status": "Available",
            "Description": "",
            "RouteTableId": "vtb-m5epr0god70hpomnn****",
            "ResourceGroupId": "rg-acfmykd63gtpfpa",
            "ZoneId": "cn-qingdao-b",
            "AvailableIpAddressCount": 252,
            "CreateTime": "2024-10-16T05:30:31Z",
            "VSwitchId": "vsw-m5eaburrn73mdpemo****",
            "CidrBlock": "172.16.24.0/24",
            "VpcId": "vpc-m5esjf3a6b380olet****",
            "VSwitchName": "",
            "RegionId": "cn-qingdao",
            "Ipv6CidrBlock": "",
            "Tags": [
              {
                "TagKey": "acs:tag:createdby",
                "TagValue": "sub:206453422934844953:user****"
              }
            ]
          }
        }
      ],
      "totalCount": 29
    }    

更新資源

  1. 調用UpdateResource,更新指定資源。調用樣本如下:

    重要

    更新資源時,請謹慎操作,避免誤操作影響其他資源。

    /**
     * 更新資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VSwitch”
     * @param resourceId       資源ID,傳入此例中建立VSwitch的ID
     * @param client           RAM使用者client
     * @return updateResourceResponse 返回對象
     */
    public UpdateResourceResponse updateResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        // 參數集合
        Map body = new HashMap();
        body.put("Description", "測試更新");
        UpdateResourceRequest updateResourceRequest = new UpdateResourceRequest()
                .setRegionId(regionId)
                .setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
        return updateResourceResponse;
    }
  2. 此次請求返回碼statusCode=200,說明請求成功,返回body如下。驗證更新結果可執行查詢資源操作,請參見查詢資源

    updateResourceResponse.getBody()

    {
      "requestId": "C97193DF-FA5A-5B9B-B822-4C128CAC371E"
    }

查詢資源

  1. 調用GetResources,查詢指定資源。調用樣本如下:

    /**
     * 查詢資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VSwitch”
     * @param resourceId       資源ID,傳入此例中建立VSwitch的ID
     * @param client           RAM使用者client
     * @return resourcesWithOptions 返回對象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        Map<String, String> body = new HashMap<>();
        GetResourcesRequest getResourcesRequest = new GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }
  2. 此次請求成功,返回body如下:

    resourcesWithOptions.getBody()

    {
      "resource": {
        "resourceId": "vsw-m5eaburrn73mdpemo****",
        "resourceAttributes": {
          "IsDefault": false,
          "Status": "Available",
          "Description": "測試更新",
          "RouteTableId": "vtb-m5epr0god70hpomnn****",
          "ResourceGroupId": "rg-acfmykd63gtpfpa",
          "ZoneId": "cn-qingdao-b",
          "AvailableIpAddressCount": 252,
          "CreateTime": "2024-10-16T05:30:31Z",
          "VSwitchId": "vsw-m5eaburrn73mdpemo****",
          "CidrBlock": "172.16.24.0/24",
          "VpcId": "vpc-m5esjf3a6b380olet****",
          "VSwitchName": "",
          "RegionId": "cn-qingdao",
          "Ipv6CidrBlock": "",
          "Tags": [
            {
              "TagKey": "acs:tag:createdby",
              "TagValue": "sub:206453422934844953:user****"
            }
          ]
        }
      },
      "requestId": "B16A5BFC-20FC-5C3A-B640-6CB014328E16"
    }

刪除資源

  1. 調用DeleteResource,刪除指定資源。調用樣本如下:

    重要

    刪除資源時,請謹慎操作,避免誤操作影響其他資源。

    /**
     * 刪除資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VSwitch”
     * @param resourceId       資源ID,傳入此例中建立VSwitch的ID
     * @param client           RAM使用者client
     * @return deleteResourceResponse 返回對象
     */
    public DeleteResourceResponse deleteResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        DeleteResourceRequest deleteResourceRequest = new DeleteResourceRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
        return deleteResourceResponse;
    }
  2. 此次調用成功,返回statusCode=202,說明為非同步作業,需要進一步查詢任務狀態,記錄taskId,用於查詢任務,請參見查詢任務

    deleteResourceResponse.getBody()

    {
      "requestId": "A9BC357C-7ED1-5046-ADDF-4BE17C5A7064",
      "taskId": "task-5057a4fbef2bcffe4562c2954****"
    }

查詢任務

查詢指定任務的任務狀態。

  1. 調用GetTask,查詢指定任務的狀態。調用樣本為查詢此教程中的建立VSwitch任務,如下:

    /**
     * 查詢非同步任務
     * @param taskId 任務Id
     * @param client RAM使用者client
     * @return taskWithOptions 返回對象
     */
    public GetTaskResponse getTask(String taskId, Client client) throws Exception {
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> headers = new HashMap<>();
        GetTaskResponse taskWithOptions = client.getTaskWithOptions(taskId, headers, runtime);
        return taskWithOptions;
    }
  2. 此次請求成功,返回body中status="Succeeded",說明任務處理完成。

    taskWithOptions.getBody()

    {
      "task": {
        "taskAction": "Create",
        "product": "VPC",
        "resourceId": "vsw-m5eaburrn73mdpemo****",
        "createTime": "2024-10-16T05:30:31Z",
        "regionId": "cn-qingdao",
        "resourcePath": "VSwitch/vsw-m5eaburrn73mdpemo****",
        "taskId": "task-5057a4fbef2bcffe44d6b3590****",
        "resourceType": "VSwitch",
        "status": "Succeeded"
      },
      "requestId": "C062613B-8A99-5E69-86DB-26446D1AB845"
    }

完整範例程式碼

本教程中完整ExampleDemo如下:

ExampleDemo

package org.example;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.HashMap;
import java.util.Map;

/**
 * 實現資源管理
 */
public class ExampleDemo {

    /**
     * 初始化帳號Client
     * @return Client
     */
    public static Client createClient() throws Exception {
        // 工程代碼泄露可能會導致 AccessKey 泄露,並威脅帳號下所有資源的安全性。以下程式碼範例僅供參考。
        Config config = new Config()
                // 必填,請確保代碼運行環境設定了環境變數 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填,請確保代碼運行環境設定了環境變數 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint 請參考 https://api.aliyun.com/product/cloudcontrol
        config.endpoint = "cloudcontrol.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 列舉產品
     * @param client 帳號client
     * @return listProductsResponse 返回對象
     */
    public ListProductsResponse listProducts(Client client) throws Exception {
        ListProductsHeaders listProductsHeaders = new ListProductsHeaders();
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        RuntimeOptions runtime = new RuntimeOptions();
        ListProductsResponse listProductsResponse = client.listProductsWithOptions("Aliyun", listProductsRequest, listProductsHeaders, runtime);
        return listProductsResponse;
    }

    /**
     * 列舉資源類型
     * @param productCode 產品code,此例中為"VPC"
     * @param client      帳號client
     * @return listResourceTypesResponse 返回對象
     */
    public ListResourceTypesResponse listResourceTypes(String productCode, Client client) throws Exception {
        com.aliyun.cloudcontrol20220830.models.ListResourceTypesHeaders listResourceTypesHeaders = new com.aliyun.cloudcontrol20220830.models.ListResourceTypesHeaders();
        com.aliyun.cloudcontrol20220830.models.ListResourceTypesRequest listResourceTypesRequest = new com.aliyun.cloudcontrol20220830.models.ListResourceTypesRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 複製代碼運行請自行列印 API 的傳回值
        ListResourceTypesResponse listResourceTypesResponse = client.listResourceTypesWithOptions("Aliyun", productCode, listResourceTypesRequest, listResourceTypesHeaders, runtime);
        return listResourceTypesResponse;
    }

    /**
     * 建立資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VPC”
     * @param client           RAM使用者client
     * @return resourceWithOptions 返回對象
     */
    public CreateResourceResponse createResource(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 參數集合
        Map body = new HashMap();
        body.put("Description", "測試建立");
        com.aliyun.cloudcontrol20220830.models.CreateResourceRequest createResourceRequest = new com.aliyun.cloudcontrol20220830.models.CreateResourceRequest()
                .setRegionId(regionId).setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        CreateResourceResponse resourceWithOptions = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
        return resourceWithOptions;
    }

    /**
     * 查詢非同步任務
     * @param taskId 任務Id
     * @param client RAM使用者client
     * @return taskWithOptions 返回對象
     */
    public GetTaskResponse getTask(String taskId, Client client) throws Exception {
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetTaskResponse taskWithOptions = client.getTaskWithOptions(taskId, headers, runtime);
        return taskWithOptions;
    }

    /**
     * 列舉資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VPC”
     * @param client           RAM使用者client
     * @return resourcesWithOptions 返回對象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode;
        // 參數集合
        Map body = new HashMap();
        body.put("VpcId", "vpc-m5er4j63farlj8d53****");
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
                .setRegionId(regionId).setFilter(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }

    /**
     * 查詢資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VPC”
     * @param resourceId       資源ID,傳入此例中建立VPC的ID
     * @param client           RAM使用者client
     * @return resourcesWithOptions 返回對象
     */
    public GetResourcesResponse getResources(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        GetResourcesResponse resourcesWithOptions = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
        return resourcesWithOptions;
    }

    /**
     * 更新資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VPC”
     * @param resourceId       資源ID,傳入此例中建立VPC的ID
     * @param client           RAM使用者client
     * @return updateResourceResponse 返回對象
     */
    public UpdateResourceResponse updateResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        // 參數集合
        Map body = new HashMap();
        body.put("Description", "測試更新");
        com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest updateResourceRequest = new com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest()
                .setRegionId(regionId).setBody(body);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
        return updateResourceResponse;
    }

    /**
     * 刪除資源
     * @param regionId         地區ID
     * @param productCode      產品code,此例中為"VPC"
     * @param resourceTypeCode 資源類型code,此例中為“VPC”
     * @param resourceId       資源ID,傳入此例中建立VPC的ID
     * @param client           RAM使用者client
     * @return deleteResourceResponse 返回對象
     */
    public DeleteResourceResponse deleteResource(String regionId, String productCode, String resourceTypeCode, String resourceId, Client client) throws Exception {
        String requestPath = "/api/v1/providers/Aliyun/products/" + productCode + "/resources/" + resourceTypeCode + "/" + resourceId;
        com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest deleteResourceRequest = new com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest()
                .setRegionId(regionId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
        return deleteResourceResponse;
    }
}