Java SDK call examples

Updated at:

This topic describes how to use the Alibaba Cloud SDK for Java to query the domain names in your account that are accelerated by CDN.

Step 1: View OpenAPI documentation

Before calling an API operation, review its documentation to understand the request parameters and required permissions. For more information, see API overview.

Step 2: Create and authorize a RAM user

Important

An Alibaba Cloud account can call all API operations. We recommend that you create a RAM user to call API operations or perform daily O&M.

If you have already created a RAM user and granted it the required permissions, skip this step.

  • Log on to the RAM console by using your Alibaba Cloud account.

  • Create a RAM user.

    • In the left-side navigation pane, choose Identities > Users.

    • On the Users page, click Create User.

    • On the Create User page, set the Logon Name and Display name, select Console Password Logon and Using permanent AccessKey to access for Access Mode, and then click OK.

      Important

      The AccessKey secret of a RAM user is displayed only once upon creation and cannot be retrieved later. Download the CSV file and store it securely.

      After creating the RAM user, record its logon name and password. To debug API calls, you must use this RAM user's credentials to log on to Alibaba Cloud OpenAPI Explorer and use its AccessKey pair.

  • Grant the RAM user permissions.

    Note

    By default, a new RAM user lacks permissions to manage CDN. You must grant permissions by using a system policy (such as AliyunCDNFullAccess or AliyunCDNReadOnlyAccess) or a custom policy. This example uses the AliyunCDNReadOnlyAccess policy, which grants read-only permissions for CDN resources.

    • On the Users page, find the RAM user that you want to authorize and click Add Permissions in the Add Permissions column.

    • In the Authorize panel, search for and select AliyunCDNReadOnlyAccess in the system policy list and click OK.

    • Check the authorization result and click close.

Step 3: Call an API operation

  • Log on to Alibaba Cloud OpenAPI Explorer as the RAM user.

  • Select CDN.

  • In the top navigation bar, choose Tool Hub > Online debugging.

  • In the left-side navigation pane, find and click DescribeUserDomains. Select China (Hangzhou) for the Service Address parameter. In the DomainName parameter, enter the domain name that you want to query. If you leave this parameter empty, the query returns all domain names in your account that are added to CDN.

  • Click Send Request.

    In the Debugging Result section, you can view the query results, request headers, and response headers. A status code of 200 indicates that the call is successful.

Step 4: Obtain SDK sample code

OpenAPI Explorer provides SDKs in multiple programming languages, such as Java, Go, Python, Node.js, TypeScript, PHP, and C++. You can integrate an SDK and call API operations by using the SDK's methods. The SDKs encapsulate the signing logic, timeout mechanism, and retry mechanism, and return structured response objects based on the documentation to streamline development.

The following section describes how to obtain the sample code for the Java SDK. The procedure is similar for other programming languages.

  • On the SDK Sample Code tab, select an SDK version and a programming language. We recommend using V2.0. For more information about the differences between V1.0 and V2.0, see Differences between SDK V1.0 and V2.0.

  • Click Download Project to download the complete SDK project. After downloading the project, decompress it.

    Note
    • In the upper-right corner of the SDK sample code section, click the image icon to copy the SDK sample code.

    • Click SDK Information to view details that help you integrate the SDK, such as its package name, version, and installation commands.

Step 5: Run the SDK sample code

This section describes how to run the Java SDK sample code.

  1. Open IntelliJ IDEA, choose File > Open, select the decompressed project folder, and then wait for Maven to automatically install the dependencies.

  2. Before you call an API operation, obtain an AccessKey pair. Use the AccessKey pair from the RAM user you created. For more information, see Create an AccessKey pair.

    Important

    After obtaining the RAM user's AccessKey pair, you must configure it in your environment variables. For more information, see Configure environment variables on a Linux, macOS, or Windows computer.

  3. Run the sample code.

    Double-click the Sample file, check for errors, and then run the code.

    // This file is auto-generated, don't edit it. Thanks.
    package com.aliyun.sample;
    
    import com.aliyun.tea.*;
    
    public class Sample {
    
        /**
         * <b>description</b> :
         * <p>Initialize Client with AK/SK</p>
         * @return Client
         *
         * @throws Exception
         */
        public static com.aliyun.cdn20180510.Client createClient() throws Exception {
            // Leaking project source code may lead to AccessKey leakage, compromising the security of all resources under your account. The following code example is for reference only.
            // It is recommended to use the more secure STS (Security Token Service) method. For more authentication methods, see: https://help.aliyun.com/document_detail/378657.html。
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Ensure that the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the runtime environment.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Ensure that the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the runtime environment.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Endpoint see https://api.aliyun.com/product/Cdn
            config.endpoint = "cdn.aliyuncs.com";
            return new com.aliyun.cdn20180510.Client(config);
        }
    
        public static void main(String[] args_) throws Exception {
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.cdn20180510.Client client = Sample.createClient();
            com.aliyun.cdn20180510.models.DescribeUserDomainsRequest describeUserDomainsRequest = new com.aliyun.cdn20180510.models.DescribeUserDomainsRequest()
                    .setDomainName("clxxxop");
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                com.aliyun.cdn20180510.models.DescribeUserDomainsResponse resp = client.describeUserDomainsWithOptions(describeUserDomainsRequest, runtime);
                com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
            } catch (TeaException error) {
                // For demonstration purposes only. Handle exceptions properly; do not suppress them in production code.
                // Error message
                System.out.println(error.getMessage());
                // Address
                System.out.println(error.getData().get("Recommend"));
            }
        }
    }
    
  4. View the results. In the console at the bottom, press Ctrl+F, search for statusCode. A result of "statusCode": 200 indicates a successful call.

    63a1fa3437fb64293addba0"},"statusCode":200,"body":{"backupPlans":{"backupPlan":[{"backupSourceGroupId":"","backupType":"COMPLETE","createdTime":1716258117,"crossAccountType":"SELF_ACCOUNT","crossAccountUserId":0,"disabled":fal