Integrate an SDK

Updated at:
Copy as MD

Integrate an Alibaba Cloud SDK to call OpenAPI operations from your Java application. SDK integration involves three steps: importing the SDK, setting access credentials, and calling API operations.

Usage notes

  • The Java (asynchronous) SDK is available only for V2.0 series SDKs.

  • The Java (asynchronous) SDK does not support OpenAPI operations that require file uploads or file URL parameters. Use the Java SDK instead.

Prerequisites

JDK 1.8 or later.

Import the SDK

  1. Log on to the SDK Center. Select the product, such as Elastic Compute Service.

  2. Install the SDK as shown in the following figure.

    image

Set access credentials

OpenAPI calls require access credentials such as AccessKey pairs or STS tokens. Store credentials as environment variables to prevent leaks. Securely use access credentials. The following example uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Configure environment variables on Linux and macOS

Set an Alibaba Cloud AccessKey in environment variables on Linux and macOS

This section uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as examples. You can replace the variable names as needed, for example, OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.

Configure environment variables by using the export command:

Important

A temporary environment variable set using the export command is valid only for the current session. The variable is cleared when the session ends. For long-term retention (LTR), add the export command to the startup configuration file of your operating system.

  • Configure the AccessKey ID and press Enter.

    # Replace yourAccessKeyID with your AccessKey ID.
    export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyID
  • Configure the AccessKey secret and press Enter.

    # Replace yourAccessKeySecret with your AccessKey secret.
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • Verify the configuration.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the command returns the correct AccessKey ID, the configuration is successful.

Configure environment variables on Windows

Use the graphical user interface (GUI)

  • Procedure

    The following steps describe how to set environment variables using the GUI in Windows 10.

    On your desktop, right-click This PC and choose Properties > Advanced system settings > Environment Variables > New under System variables or User variables. Then, complete the configuration.

    Variable

    Example value

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: yourAccessKeyID

    AccessKey secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Use the command prompt (CMD)

  • Procedure

    Open the command prompt as an administrator and run the following commands to add new environment variables to the system.

    setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M

    The /M parameter indicates a system environment variable. You can omit this parameter when you set a user environment variable.

  • Test the configuration

    Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the commands return the correct AccessKey, the configuration is successful.

Use Windows PowerShell

In PowerShell, you can set new environment variables that are valid for all new sessions:

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::User)

To set environment variables for all users, you must have administrative permissions:

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

You can set temporary environment variables that are valid only for the current session:

$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"

In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the commands return the correct AccessKey, the configuration is successful.

Note

Restart your development tool after you complete the configuration.

Use the SDK

The following example calls the DescribeInstances API of Elastic Compute Service. DescribeInstances API reference: DescribeInstances.

1. Initialize the asynchronous client

All OpenAPI calls go through the async client, which requires a credential provider. The following example uses a static credential provider. Manage access credentials.

Note
  • The async client is thread-safe. Use a singleton per credential-and-Endpoint pair to avoid redundant initialization.

  • The SDK uses a connection pool for async HTTP requests. Customize pool parameters in HTTP connection pool configuration.

  • Additional async client options: Advanced configuration.

// Static credential provider
com.aliyun.auth.credentials.provider.StaticCredentialProvider provider = com.aliyun.auth.credentials.provider.StaticCredentialProvider.create(
  com.aliyun.auth.credentials.Credential.builder()                                                                                                                                        
  // Required. This example shows how to obtain the AccessKey ID from an environment variable.
  .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
  // Required. This example shows how to obtain the AccessKey secret from an environment variable.
  .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
  .build());

// Initialize the client
com.aliyun.sdk.service.ecs20140526.AsyncClient client = com.aliyun.sdk.service.ecs20140526.AsyncClient.builder()
  .credentialsProvider(provider)
  .overrideConfiguration(
    darabonba.core.client.ClientOverrideConfiguration.create()
    // Endpoint configuration
    .setEndpointOverride("ecs.cn-hangzhou.aliyuncs.com")
  )
  .build();

2. Create a request object

Pass parameters through the SDK request object, which follows the naming pattern <OpenAPI Name>Request. For example, DescribeInstances uses DescribeInstancesRequest. For parameter details, check the API documentation: DescribeInstances.

com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesRequest describeInstancesRequest = com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesRequest.builder()
  .regionId("cn-hangzhou")
  .build();

3. Send the request

Call an API operation by invoking the camelCase method on the client. Pass the request object from the previous step as the input parameter.

try {
  java.util.concurrent.CompletableFuture<com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponse> response = client.describeInstances(describeInstancesRequest);
  // Obtain the result
  response.thenAccept(resp -> {
    System.out.println(new Gson().toJson(resp));
  }).exceptionally(throwable -> { 
    // Handling exceptions
    System.out.println(throwable.getMessage());
    return null;
  });
} finally {
  client.close();
}

4. Handle exceptions

Asynchronous calls can throw ClientException and ServerException.

Important

Handle exceptions properly—propagate, log, or recover from them to maintain system stability.

Complete code sample

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.gateway.pop.exception.PopClientException;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponse;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.google.gson.Gson;
import darabonba.core.exception.ValidateException;

public class Demo {

  private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
  private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
  private static final String ENDPOINT = "ecs.cn-hangzhou.aliyuncs.com";

  public static void main(String[] args) {
    // Initialize the credential provider
    StaticCredentialProvider credentialProvider = StaticCredentialProvider.create(
      Credential.builder()
      .accessKeyId(ACCESS_KEY_ID)
      .accessKeySecret(ACCESS_KEY_SECRET)
      .build()
    );

    // Build the asynchronous client configuration
    AsyncClient client = AsyncClient.builder()
      .credentialsProvider(credentialProvider)
      .overrideConfiguration(
        ClientOverrideConfiguration.create()
        .setEndpointOverride(ENDPOINT)
      )
      .build();

    // Build the request object
    DescribeInstancesRequest request = DescribeInstancesRequest.builder()
      .regionId("cn-hangzhou")
      .build();

    try {
      // Send an asynchronous request
      CompletableFuture<DescribeInstancesResponse> response = client.describeInstances(request);
      response.thenAccept(resp -> {
        System.out.println(new Gson().toJson(resp));
      }).exceptionally(throwable -> { 
        // Handling exceptions
        System.out.println(throwable.getMessage());
        return null;
      });
    } finally {
      client.close();
    }
  }
}