Alibaba Cloud SDK for Java (V1.0)

repository·master·Indexed 23 days ago

https://github.com/aliyun/aliyun-openapi-java-sdk

The Alibaba Cloud SDK for Java (V1.0) enables interaction with services such as ECS, SLB, and CloudMonitor by automating API signing and request construction. It requires JDK 1.6 or higher (JDK 1.8+ recommended) and supports authentication via AccessKey, STS Tokens, and Bearer Tokens (for CCC). Note that V1.0 is currently in maintenance mode, and migration to the V2.0 Java SDK is recommended for new projects.

Tokens
16.7K
Snippets
33
Records
53
Agent score
77%

What's inside aliyun-openapi-java-sdk

  1. Use the default credential provider chain

    master

    If you do not explicitly provide credentials, the SDK uses a default provider chain to look for credentials in the following order:

    1. System Properties: Checks for alibabacloud.accessKeyId and alibabacloud.accessKeyIdSecret.
    2. Environment Credentials: Checks for ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
    3. Credentials File: Looks for a configuration file at ~/.alibabacloud/credentials (or C:\Users\USER_NAME\.alibabacloud\credentials on Windows).
      • You can change the file path using the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable.
      • You can select a specific profile using the ALIBABA_CLOUD_PROFILE environment variable.
    4. Instance RAM Role: If ALIBABA_CLOUD_ECS_METADATA is defined, the SDK fetches temporary security credentials from the ECS metadata service.

    To use the default chain, simply initialize the client with a region ID:

    IAcsClient client = new DefaultAcsClient("your-region-id");
  2. Configure the connection pool for DefaultAcsClient

    master

    Multiple SDK clients share the same connection pool. You can configure pool parameters such as maxRequestsPerHost, connectionTimeoutMillis, and maxIdleConnections during the initialization phase by using HttpClientConfig. This configuration is applied to the DefaultProfile before creating the DefaultAcsClient.

    // Create and initialize a DefaultAcsClient instance
    DefaultProfile profile = DefaultProfile.getProfile(
    "<your-region-id>",          // The region ID
    "<your-access-key-id>",      // The AccessKey ID of the RAM account
    "<your-access-key-secret>"); // The AccessKey Secret of the RAM account
    
    // Multiple SDK clients share the same connection pool, set the
    // parameters for this pool here such as maxRequestsPerHost, timeout, etc.
    HttpClientConfig clientConfig = HttpClientConfig.getDefault();
    clientConfig.setMaxRequestsPerHost(6);
    clientConfig.setConnectionTimeoutMillis(30000L);
    clientConfig.setMaxIdleConnections(20);
    
    profile.setHttpClientConfig(clientConfig);
    IAcsClient client = new DefaultAcsClient(profile);
  3. Enable and configure logging for DefaultAcsClient

    master

    To enable logging in the Aliyun Java SDK, you must provide an implementation of the org.slf4j.Logger interface to the IClientProfile object. You can also customize the log format using setLogFormat.

    Steps:

    1. Create an IClientProfile using DefaultProfile.getProfile.
    2. Pass your SLF4J logger implementation via profile.setLogger(logger).
    3. (Optional) Set a custom log format via profile.setLogFormat(format).
    4. Initialize DefaultAcsClient with the profile.
    IClientProfile profile = DefaultProfile.getProfile(regionId, accesskeyId, accesskeySecret);
    // Client Logger配置
    profile.setLogger(logger);
    // Client 日志格式配置
    profile.setLogFormat(format);
    DefaultAcsClient client = new DefaultAcsClient(profile);
    client.getAcsResponse(request);
  4. Migration from V1.0 to V2.0 Java SDK

    master

    ⚠️ Important Notice: Alibaba Cloud SDK for Java (V1.0) has entered a basic security maintenance phase and is no longer recommended for new users.

    Why migrate to V2.0?

    • Better Performance: Improved architecture and optimized performance.
    • Enhanced Security: Modern security practices and credential management.
    • Continuous Maintenance: Ongoing updates and bug fixes.
    • Rich Features: New features and improved API designs.

    Migration Resources

  5. Install the Aliyun Java SDK via Maven

    master

    To use any Alibaba Cloud product SDK, you must install the aliyun-java-sdk-core library in addition to the specific product SDK (e.g., aliyun-java-sdk-ecs). Add the following dependencies to your pom.xml file.

    If your Maven environment is not automatically downloading JAR packages from a central repository, you must also explicitly include the gson dependency to avoid NoClassDefFoundError exceptions.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>[4.3.2,5.0.0)</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-ecs</artifactId>
        <version>[4.16.0,5.0.0)</version>
    </dependency>
    
    <!-- Required if Maven fails to download JARs from central repository to avoid NoClassDefFoundError -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
  6. Customize the Endpoint for API requests

    master

    You can override the default endpoint used for API requests using two methods.

    1. Global Configuration: Use DefaultProfile.addEndpoint to set a specific endpoint for a product in a specific region across your entire application.
    2. Request-level Configuration: Use setSysEndpoint on a specific request object to override the endpoint only for that individual call. This has the highest priority.

    用户自定义 (User Customization) is the highest priority addressing logic.

    // 全局生效 (Global effect)
    DefaultProfile.addEndpoint("<RegionID>", "<Product>", "<Endpoint>");
    
    // 只对当前 Request 生生效 (Only for current Request)
    DescribeRegionsRequest request = new DescribeRegionsRequest();
    request.setSysEndpoint("<Endpoint>");
  7. Configure the logger in DefaultAcsClient

    master

    To enable logging in the Aliyun Java SDK, you must provide an implementation of the org.slf4j.Logger interface to the IClientProfile object before initializing the DefaultAcsClient. You can also optionally specify a custom log format using setLogFormat.

    IClientProfile profile = DefaultProfile.getProfile(regionId, accesskeyId, accesskeySecret);
    // configure logger
    profile.setLogger(logger);
    // configure log format
    profile.setLogFormat(format);
    DefaultAcsClient client = new DefaultAcsClient(profile);
    client.getAcsResponse(request);
  8. Quick Start: Call an Alibaba Cloud API (V1.0)

    master

    The standard workflow for using the V1.0 SDK involves three main steps:

    1. Initialize a DefaultAcsClient instance using a DefaultProfile.
    2. Create an API request object and set the required parameters.
    3. Execute the request using the client and handle ServerException or ClientException.

    Security Note: Do not hardcode credentials in your source code. Use external configurations or environment variables instead.

    package com.testprogram;
    
    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 Main {
        public static void main(String[] args) {
            // 1. Create and initialize DefaultAcsClient instance.
            DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>",          // Region ID
                "<your-access-key-id>",      // RAM AccessKey ID
                "<your-access-key-secret>"); // RAM AccessKey Secret
            IAcsClient client = new DefaultAcsClient(profile);
    
            // 2. Create API request and set parameters
            DescribeInstancesRequest request = new DescribeInstancesRequest();
            request.setPageSize(10);
    
            // 3. Send request and handle response or exceptions
            DescribeInstancesResponse response;
            try {
                response = client.getAcsResponse(request);
                for (DescribeInstancesResponse.Instance instance:response.getInstances()) {
                    System.out.println(instance.getPublicIpAddress());
                }
            } catch (ServerException e) {
                e.printStackTrace();
             } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  9. Authenticate using Bearer Token (CCC product only)

    master

    For products that support Bearer Token authentication (specifically the CCC product), you can initialize the DefaultAcsClient using a BearerTokenCredentials object alongside a DefaultProfile.

    package com.testprogram;
    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.ccc.model.v20170705.ListPhoneNumbersRequest;
    import com.aliyuncs.ccc.model.v20170705.ListPhoneNumbersResponse;
    
    public class Main {
        public static void main(String[] args) {
            // Initialize profile with region ID
            DefaultProfile profile = DefaultProfile.getProfile("<your-region-id>");
            
            // Create BearerTokenCredentials
            BearerTokenCredentials bearerTokenCredential = new BearerTokenCredentials("<your-bearer-token>");
            
            // Initialize client with profile and bearer token
            DefaultAcsClient client = new DefaultAcsClient(profile, bearerTokenCredential);
            
            // Create API request
            ListPhoneNumbersRequest request = new ListPhoneNumbersRequest();
            request.setInstanceId("yourId");
            request.setOutboundOnly(true);
            
            ListPhoneNumbersResponse response;
            try {
                response = client.getAcsResponse(request);
                // Handle response logic
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  10. Configure proxy settings for the Aliyun Java SDK

    master

    You can configure proxy settings for the Aliyun Java SDK using either HttpClientConfig (highest priority) or environment variables.

    Using HttpClientConfig

    Use HttpClientConfig.getDefault() to create a configuration object, then apply it to your IClientProfile before initializing the DefaultAcsClient.

    Using Environment Variables

    If no client-side configuration is provided, the SDK respects the following environment variables:

    1. HTTP_PROXY or http_proxy
    2. HTTPS_PROXY
    3. NO_PROXY

    Note: Client-side configuration takes precedence over environment variables.

    // Client 代理配置
    HttpClientConfig clientConfig = HttpClientConfig.getDefault();
    // 设置HTTP代理
    clientConfig.setHttpProxy("http://127.0.0.1:9898");
    // 设置HTTPS代理
    clientConfig.setHttpsProxy("http://user:password@127.0.0.1:8989");
    // 设置忽略代理地址列表
    clientConfig.setNoProxy("127.0.0.1,localhost");
    
    IClientProfile profile = DefaultProfile.getProfile(regionId, accesskeyId, accesskeySecret);
    profile.setHttpClientConfig(clientConfig);
    DefaultAcsClient client = new DefaultAcsClient(profile);
  11. Manually define an API Endpoint

    master

    You can specify a custom endpoint for service APIs. This is the highest-priority method and allows you to override the default endpoint resolution logic. You can apply this globally to all requests using a profile or locally to a specific request object.

    // Global effect: applies to all requests using this profile
    DefaultProfile.addEndpoint("<RegionID>", "<Product>", "<Endpoint>");
    
    // Local effect: applies only to the current request
    DescribeRegionsRequest request = new DescribeRegionsRequest();
    request.setSysEndpoint("<Endpoint>");