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
-
Log on to SDK Center and select the product that you want to use, such as Short Message Service (SMS).
-
On the Install page, set All Languages to Java. Then, on the Quick Start tab, find the Short Message Service (SMS) SDK installation method.

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
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=yourAccessKeyIDConfigure the AccessKey secret and press Enter.
# Replace yourAccessKeySecret with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecretVerify the configuration.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_IDcommand. 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%andecho %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 /MThe
/Mparameter 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%andecho %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.
-
`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.
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.
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.
Always handle exceptions properly—propagate, log, or recover—to maintain system stability.
View the complete code sample
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:
Temporary files in OSS are cleared periodically.
-
Initialize the request client
Set both
regionIdandendpoint. TheregionIddetermines the OSS region for temporary file storage. IfregionIdis 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); } -
Create a request object
Create an
<OpenAPIName>AdvanceRequestobject to pass the file stream. Check the<OpenAPIName>AdvanceRequestsource file for parameter names and types. For example,DetectBodyCountAdvanceRequestacceptsimageURLObjectof typeInputStream.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. -
Initiate a request
Call the
<apiName>Advancemethod 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);
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 ofXXXfrom environment variables.
Additional troubleshooting: FAQ.