All Products
Search
Document Center

Alibaba Cloud SDK:Integrate an SDK

Last Updated:Jun 02, 2026

Integrate an Alibaba Cloud SDK into your project to call OpenAPI operations. The integration involves three steps: import the SDK, set access credentials, and call the API.

Prerequisites

JDK 1.8 or later.

Import the SDK

  1. Log on to SDK Center and select the product that you want to use, such as Short Message Service (SMS).

  2. On the Install page, set All Languages to Java. Then, on the Quick Start tab, find the Short Message Service (SMS) SDK installation method.image

Set access credentials

Calling an OpenAPI requires access credentials such as AccessKey and Security Token Service (STS) token. Store credentials as environment variables to prevent leaks. Security best practices are covered in Securely use access credentials. The following example uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables:

Configuration method in Linux and macOS

Configure environment variables 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.

Configuration method in 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.

Using 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.

Use the SDK

The following example calls the SendMessageToGlobe API of Short Message Service (SMS) . SendMessageToGlobe API reference: SendMessageToGlobe.

1. Initialize the request client

All OpenAPI calls originate from a request client (Client). This example initializes the client with an AccessKey. Other initialization methods are described in Manage access credentials.

Important
  • `Client` instances are thread-safe and can be shared across threads.

  • Avoid creating `Client` objects repeatedly with `new`. Use the singleton pattern to reuse one client per set of credentials and endpoint.

public static com.aliyun.dysmsapi20180501.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    // See https://api.alibabacloud.com/product/Dysmsapi.
    config.endpoint = "dysmsapi.aliyuncs.com";
    return new com.aliyun.dysmsapi20180501.Client(config);
}

2. Create a request object

Pass parameters through the SDK request object, named in the <OpenAPIName>Request format (e.g., SendSmsRequest for SendSms). Request parameter details: SendMessageToGlobe.

Note

If an API has no request parameters, skip the request object (e.g., DescribeCdnSubList).

com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest sendMessageToGlobeRequest = new com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest()
                .setTo("8521245567****")
                .setMessage("Hello");

3. Send a request

Call the API using a method in the <apiName>WithOptions format, where <apiName> is the camelCase API name. This method takes the request object and a runtime parameter that controls timeout, proxy, and other settings. Runtime options are detailed in Advanced configuration.

Note

If an API has no request parameters, pass only the runtime parameter (e.g., DescribeCdnSubList).

Response objects follow the <OpenAPIName>Response naming convention (e.g., SendSmsResponse).

com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
Client client = createClient();
// call  api
client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);

4. Handle exceptions

The Java SDK has two exception types: `TeaUnretryableException` and `TeaException`.

  • `TeaUnretryableException`: Thrown after all retries are exhausted, typically due to network issues.

  • `TeaException`: Thrown for business logic errors.

Exception handling patterns are detailed in Exception handling.

Important

Always handle exceptions properly—propagate, log, or recover—to maintain system stability.

View the complete code sample

Sample call of the SendMessageToGlobe API

import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;

public class Sample {
    public static Client createClient() throws Exception {
        Config config = new Config()
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // See https://api.alibabacloud.com/product/Dysmsapi.
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static void main(String[] args_) {
        try {
            Client client = Sample.createClient();
            SendMessageToGlobeRequest sendMessageToGlobeRequest = new SendMessageToGlobeRequest()
                    .setTo("8521245567****")
                    .setMessage("Hello");
            RuntimeOptions runtime = new RuntimeOptions();

            SendMessageToGlobeResponse sendMessageToGlobeResponse = client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
            System.out.println(new Gson().toJson(sendMessageToGlobeResponse.body));
        } catch (TeaUnretryableException ue) {
            // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
            ue.printStackTrace();
            // print error message
            System.out.println(ue.getMessage());
            System.out.println(ue.getLastRequest());
        } catch (TeaException e) {
            // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
            e.printStackTrace();
            // print error message
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            System.out.println(e.getData());
        } catch (Exception e) {
            // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
            e.printStackTrace();
        }
    }
}

File uploads with the Advance interface

Some products (e.g., Image Search, Visual Intelligence API) do not directly support file uploads via their standard OpenAPI. Use the Advance interface to pass a file stream instead. The cloud product temporarily stores the uploaded file in Alibaba Cloud OSS (default region: cn-shanghai) and reads it from there. The following example uses DetectBodyCount from Visual Intelligence API - Face and Body:

Note

Temporary files in OSS are cleared periodically.

  1. Initialize the request client

    Set both regionId and endpoint. The regionId determines the OSS region for temporary file storage. If regionId is not set, region mismatch between the product and OSS can cause timeouts.

    public static com.aliyun.facebody20191230.Client createClient() throws Exception {
         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                 // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") gets the AccessKey ID from the environment variable.
                 .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                 // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") gets the AccessKey secret from the environment variable.
                 .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
         config.regionId = "cn-shanghai";
         config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
         return new com.aliyun.facebody20191230.Client(config);
    }
  2. Create a request object

    Create an <OpenAPIName>AdvanceRequest object to pass the file stream. Check the <OpenAPIName>AdvanceRequest source file for parameter names and types. For example, DetectBodyCountAdvanceRequest accepts imageURLObject of type InputStream.

    com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest detectBodyCountAdvance = new com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest()
            .setImageURLObject(Files.newInputStream(Paths.get("<FILE_PATH>"))); // Replace <FILE_PATH> with the actual file path.
  3. Initiate a request

    Call the <apiName>Advance method to send the request.

    com.aliyun.facebody20191230.Client client = createClient();
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    // Initiate the request.
    com.aliyun.facebody20191230.models.DetectBodyCountResponse resp = client.detectBodyCountAdvance(detectBodyCountAdvance, runtime);

View the complete code sample

/**
 * <dependency>
 *   <groupId>com.aliyun</groupId>
 *   <artifactId>facebody20191230</artifactId>
 *   <version>5.1.2</version>
 * </dependency>
 */

import com.aliyun.tea.*;
import com.google.gson.Gson;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Sample {

    public static com.aliyun.facebody20191230.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") gets the AccessKey ID from the environment variable.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") gets the AccessKey secret from the environment variable.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.regionId = "cn-shanghai";
        config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
        return new com.aliyun.facebody20191230.Client(config);
    }

    public static void main(String[] args_) {
        try {
            com.aliyun.facebody20191230.Client client = Sample.createClient();
            com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest detectBodyCountAdvance = new com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest()
                    .setImageURLObject(Files.newInputStream(Paths.get("<FILE_PATH>")));  // Replace <FILE_PATH> with the actual file path.
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.facebody20191230.models.DetectBodyCountResponse resp = client.detectBodyCountAdvance(detectBodyCountAdvance, runtime);
            System.out.println(new Gson().toJson(resp.body));
        } catch (TeaUnretryableException ue) {
            ue.printStackTrace();
            // Print the error message.
            System.out.println(ue.getMessage());
            // Print the request record to query the request information when an error occurs.
            System.out.println(ue.getLastRequest());
        } catch (TeaException e) {
            e.printStackTrace();
            // Print the error code.
            System.out.println(e.getCode());
            // Print the error message, which includes the RequestId.
            System.out.println(e.getMessage());
            // Print the specific error content returned by the server.
            System.out.println(e.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

FAQ

  • The error message "You are not authorized to perform this operation." is returned when I call an OpenAPI.

    Cause: The RAM user associated with your AccessKey lacks the required API permissions.

    Solution: Grant the required permissions to the RAM user. Grant permissions to a RAM user.

    For example, to authorize the SendMessageToGlobe API, create the following custom policy:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  • The error message "The specified endpoint can't operate this region." is returned when I call an OpenAPI.

    Cause: The specified endpoint does not support the target region.

    Solution: Update the endpoint as described in Endpoint configuration and retry.

  • The error message "java.lang.NullPointerException..." is returned when I call an OpenAPI.

    Cause: Your AccessKey was not passed correctly.

    Solution: Verify that the AccessKey is passed correctly during client initialization. System.getenv("XXX") reads the value of XXX from environment variables.

Additional troubleshooting: FAQ.